c语言常见的几种排序方法总结
一:选择排序和冒泡排序
这两种排序比较简单,直接贴出代码:
1 #include <stdio.h> 2 3 void choose_sort(int *arr, int n); 4 void bubble_sort(int *arr, int n); 5 void show(int *arr, int n); 6 7 int main() 8 { 9 int arr[10] = {10, 8, 3, 15, 18, 16, 11, 9, 7, 6}; 10 11 /*选择排序*/ 12 choose_sort(arr, 10); 13 show(arr, 10); 14 15 /*冒泡排序*/ 16 bubble_sort(arr, 10); 17 show(arr, 10); 18 19 return 0; 20 } 21 22 void choose_sort(int *arr, int n) 23 { 24 int i = 0; 25 int j = 0; 26 int index = 0; 27 int swap = 0; 28 29 for(i = 0; i < n; i++) { 30 index = i; 31 for(j = i; j <n; j++ ) { 32 if(arr[index] > arr[j]) { 33 index = j; 34 } 35 } 36 swap = arr[i]; 37 arr[i] = arr[index]; 38 arr[index] = swap; 39 } 40 } 41 42 void bubble_sort(int *arr, int n) 43 { 44 int i = 0; 45 int j = 0; 46 int swap = 0; 47 48 for(i = 0; i < n - 1; i++) { 49 for(j = 0; j < n - i - 1; j++) { 50 if(arr[j] > arr[j + 1]) { 51 swap = arr[j]; 52 arr[j] = arr[j + 1]; 53 arr[j + 1] = swap; 54 } 55 } 56 } 57 } 58 59 void show(int *arr, int n) 60 { 61 int i = 0; 62 for(i = 0; i < n; i++) { 63 printf("%d ", arr[i]); 64 } 65 printf("\n"); 66 }
二:插入排序
下面代码是在一个有序数组中的插入一个数,插入后仍然有序:
1 #include <stdio.h> 2 3 void insert_sort(int *arr, int num, int n); 4 5 int main() 6 { 7 int arr[10] = {1, 2, 4, 6, 8, 9, 12, 15, 19}; 8 insert_sort(arr, 20, 9); 9 10 int i = 0; 11 for(i = 0; i < 10; i++) { 12 printf("%d ", arr[i]); 13 } 14 printf("\n"); 15 16 return 0; 17 } 18 19 void insert_sort(int *arr, int num, int n) 20 { 21 int i = 0; 22 int index = 0; 23 24 for(i = 0; i < n; i++) { 25 if(arr[i] > num) { 26 index = i; 27 break; 28 } 29 } 30 31 if(i == n) { 32 arr[i] = num; 33 } 34 else { 35 for(i = n; i >= index; i--) { 36 arr[i + 1] = arr[i]; 37 } 38 arr[index] = num; 39 } 40 }
三:快速排序
1 #include <stdio.h> 2 3 void quick_sort(int *arr, int low, int high); 4 void show(int *arr, int n); 5 6 int main() 7 { 8 int arr[8] = {8, 3, 9, 4, 10, 7, 6, 1}; 9 10 quick_sort(arr, 0, 7); 11 show(arr, 8); 12 13 return 0; 14 } 15 16 void quick_sort(int *arr, int low, int high) 17 { 18 int pivot = 0; 19 int i = 0; 20 int j = 0; 21 if(high <= low) 22 return; 23 24 pivot = arr[low]; 25 i = low; 26 j = high; 27 28 while(i < j) { 29 while(i < j && arr[j] > pivot) 30 j--; 31 if(i < j) 32 arr[i++] = arr[j]; 33 while(i < j && arr[i] < pivot) 34 i++; 35 if(i < j) 36 arr[j--] = arr[i]; 37 } 38 arr[i] = pivot; 39 quick_sort(arr, low, i - 1); 40 quick_sort(arr, i + 1, high); 41 } 42 43 void show(int *arr, int n) 44 { 45 int i = 0; 46 for(i = 0; i < n; i++) { 47 printf("%d ", arr[i]); 48 } 49 printf("\n"); 50 }
快速排序涉及到递归调用,比较难理解,最好在纸上画出执行过程,慢慢理解