冒泡排序
// int array[] = {3, 5, 1, 6, 8, 2, 4, 9, 7};
// int count = sizeof(array) / sizeof(array[0]);
// int flag = 0; // 有序标志位 0无序 1有序
// for ( int i = 0; flag == 0 && i < count - 1; i++) {
// flag = 1; // 假定有序
// for (int j = 0; j < count - i - 1; j++) {
// if (array[j] > array[j + 1]) {
// int temp = array[j];
// array[j] = array[j + 1];
// array[j + 1] = temp;
// flag = 0; // 确定无序
// }
// }
// }
for (int i = 0; i < count; i++) {
// printf("%d\n", array[i]);
// }
选择排序
// int array[] = {3, 5, 1, 6, 8, 2, 4, 9, 7};
// int count = sizeof(array) / sizeof(array[0]);
// for (int j = 0; j < count - 1; j++) {
// int minIndex = j;
// for (int i = minIndex + 1; i < count; i++) {
// if (array[minIndex] > array[i]) {
// minIndex = i;
// }
// }
// if (minIndex != j) {
// int temp = 0;
// temp = array[minIndex];
// array[minIndex] = array[j];
// array[j] = temp;
// }
// }
for (int i = 0; i < count; i++) {
// printf("%d\n", array[i]);
// }
折半查找
// int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// int count = sizeof(a) / sizeof(a[0]);
// int t = 8;
// int start = 0;
// int end = count - 1;
// int mid = 0;
// while (start <= end) {
// mid = (start + end) / 2;
// if (a[mid] < t) {
// start = mid + 1;
// } else if(a[mid] > t){
// end = mid - 1;
// } else {
// break;
// }
// }
// if (start <= end) {
// printf("[%2d] = %d\n", mid, t);
// } else {
// printf("not found\n");
// }
插入排序
// int array[] = {3, 5, 1, 6, 8, 2, 4, 9, 7};
// int count = sizeof(array) / sizeof(array[0]);
// for (int i = 1; i < count; i++) {
// int j = i;
// int temp = array[j];
// while (j > 0 && array[j - 1] > temp) {
// array[j] = array[j - 1];
// j--;
// }
// array[j] = temp;
// }
// for (int i = 0; i < count; i++) {
// printf ("%d\n", array[i]);
// }
快速排序
void quickSort (int array[], int count){
if (count < 2) {
return;
}
int start = 0;
int end = count - 1;
int temp = array[start];
while(start < end) {
while(start < end && array[end] > temp) {
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
while(start < end && array[start] < temp) {
start++;
}
if (start < end) {
array[end] = array[start];
end--;
}
}
array[start] = temp;
quickSort(array, start);
quickSort(array + start + 1, count - start - 1);
}
打乱顺序
// int a[] = {0,1,2,3,4,5,6,7,8,9};
// int count = sizeof(a) / sizeof(a[0]);
// for (int i = count - 1; i > 0; i--) {
// unsigned int random = arc4random() % (i + 1);
// int temp = a[random];
// a[random] = a[i];
// a[i] = temp;
// }
// for (int i = 0; i < count ; i++) {
// printf("%d\n", a[i]);
// }