排序算法1——插入排序,希尔排序
插入排序:
#include <iostream> using namespace std; void insert(int *arry, int lo, int current) { while (lo >= 0 && arry[lo] < current) { arry[lo + 1] = arry[lo]; lo--; } arry[lo + 1] = current; } void print(int *arry, int size) { for (int i = 0; i < size; i++) cout << arry[i]; cout << endl; } void main() { int arry[5] = { 3, 4, 1, 2, 5 }; print(arry, 5); for (int i = 1; i < 5; i++) insert(arry, i-1, arry[i]); print(arry, 5); system("pause"); }
希尔排序:
#include <iostream> using namespace std; void shellsort(int *arry, int size) { for (int gap = 3; gap > 0;gap--) for (int i = 0; i < gap; i++) { for (int j = i + gap; j < size; j = j + gap) { if (arry[j] < arry[j - gap]) { int temp = arry[j]; arry[j] = arry[j - gap]; arry[j - gap] = temp; for (int k = j - gap; k >= 0; k = k - gap) { if (arry[k] < arry[k - gap]) { int temp2 = arry[k]; arry[k] = arry[k - gap]; arry[k - gap] = temp2; } } } } } } void print(int *arry, int size) { for (int i = 0; i < size; i++) cout << arry[i]; cout << endl; } void main() { int arry[6] = { 2, 5, 1, 3, 4, 6 }; print(arry, 6); shellsort(arry, 6); print(arry, 6); system("pause"); }