安卓快速排序與冒泡排序
阿新 • • 發佈:2018-08-03
java int end star ear cal ber instance pretty main
冒泡排序
private void swap(int[] arrays, int i, int j) {
int temp;
temp = arrays[i];
arrays[i] = arrays[j];
arrays[j] = temp;
}
public int[] arrayIntSort(int[] array) {
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < array.length - i; j++) {
if (array[j] > array[j + 1]) {
swap(array, j, j + 1);
}
}
}
return array;
}
快速排序
private void quickSort(int[] array, int start, int end) {
int left = start;
int right = end;
if (left < right) {
int temp = array[left];
while (left != right) {
while (left < right && temp <= array[right])
right--;
array[left] = array[right];
while (left < right && temp >= array[left])
left++;
array[right] = array[left];
}
array[right] = temp;
quickSort(array, start, left - 1);
quickSort(array, right + 1, end);
}
}
c++冒泡排序寫法
void swap(jint *arrays, int i, int j) {
int temp;
temp = arrays[i];
arrays[i] = arrays[j];
arrays[j] = temp;
}
JNIEXPORT jintArray JNICALL
Java_com_cpf_ndkdemo_MainActivity_arrayIntSortByNative(JNIEnv *env, jobject instance,
jintArray array_) {
jint *array = env->GetIntArrayElements(array_, NULL);
int length = env->GetArrayLength(array_);
for (int i = 1; i < length; i++) {
for (int j = 0; j < length - i; j++) {
if (array[j] > array[j + 1]) {
swap(array, j, j + 1);
}
}
}
jintArray jintArray = env->NewIntArray(length);
env->SetIntArrayRegion(jintArray, 0, length, array);
env->ReleaseIntArrayElements(array_, array, 0);
return jintArray;
}
c++快速排序寫法
void fastSort(jint *array, jint start, jint end) {
int left = start;
int right = end;
if (left < right) {
int temp = array[left];
while (left != right) {
while (left < right && temp <= array[right])
right--;
array[left] = array[right];
while (left < right && temp >= array[left])
left++;
array[right] = array[left];
}
array[right] = temp;
fastSort(array, start, left - 1);
fastSort(array, right + 1, end);
}
}
JNIEXPORT jintArray JNICALL
Java_com_cpf_ndkdemo_MainActivity_arrayFastIntSortByNative(JNIEnv *env, jobject instance,
jintArray array_, jint start,
jint end) {
jint *array = env->GetIntArrayElements(array_, NULL);
fastSort(array, start, end);
jintArray jintArray = env->NewIntArray(end + 1);
env->SetIntArrayRegion(jintArray, 0, end + 1, array);
env->ReleaseIntArrayElements(array_, array, 0);
return jintArray;
}
快速排序波動大,冒泡排序更穩定,數據量越大快速排序速度優勢越明顯;
在數據大多數順序正確的情況下冒泡排序可能更快,而數據越混亂快速排序越快;
安卓快速排序與冒泡排序