程式設計基礎36 關於幾種排序總結
阿新 • • 發佈:2018-11-17
1,冒泡,選擇,插入排序
#include<cstdio> #include<algorithm> using namespace std; const int max_n = 5; int random_arr[max_n]; void bubbleSort(int arr[],int num) { for (int i = 1; i < num; i++) { for (int j = 0; j < num - i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } void selectSort(int arr[], int num) { for (int i = 0; i < num; i++) { int k = i; for (int j = i; j < num; j++) { if (arr[j] < arr[k]) { k = j; } } int temp = arr[k]; arr[k] = arr[i]; arr[i] = temp; } } void insertSort(int arr[], int num) { for (int i = 1; i < num; i++) { int temp = arr[i], j = i; while (j > 0 && temp < arr[j - 1]) { arr[j] = arr[j - 1]; j--; } arr[j] = temp; } } int main() { int num = 0; scanf("%d", &num); for (int i = 0; i < num; i++) { scanf("%d", &random_arr[i]); } // bubbleSort(random_arr, 5); // selectSort(random_arr, 5); // insertSort(random_arr, 5); for (int i = 0; i < num; i++) { printf("%d", random_arr[i]); if (i != num - 1) { printf(" "); } } return 0; }