7.C/C++排序

来源:互联网 发布:淘宝爱逛街发布宝贝 编辑:程序博客网 时间:2024/05/29 02:48

1.直接插入排序

//1.直接插入排序#include<iostream>using namespace std;void insert_sort(int a[], int n){int i, j, temp;for (i = 1; i < n; i++){temp = a[i];for (j = i-1 ; j >= 0 && temp < a[j]; j--){a[j + 1] = a[j];//a[j] = temp; //这一句和for循环外的a[j+1]=temp,重复,当退出循环是,j--,然后在a[j+1]=temp             //这和在循环中执行a[j]=temp的效果是一样的。}a[j+1] = temp;}}void print_array(int a[], int len){for (int i = 0; i < len; i++){cout << a[i] << " ";}cout << endl;}int main(){int a[] = { 7,3,5,8,9,1,2,4,6 };cout << "before insert sort: ";print_array(a, 9);insert_sort(a, 9);  //进行直接排序cout << "after insert sort: ";print_array(a, 9);return 0;}

before insert sort: 7 3 5 8 9 1 2 4 6
after insert sort: 1 2 3 4 5 6 7 8 9



2.希尔(Shell)排序

//2.希尔(Shell)排序#include<iostream>using namespace std;void shell_sort(int a[], int len){int h, i, j, temp;for (h = len / 2; h > 0; h = h / 2)  //控制增量{for (i = h; i < len; i++)   //这个for循环就是前面的直接插入排序{temp = a[i];for (j = i - h; j >= 0 && temp < a[j]; j-=h){a[j + h] = a[j];}a[j + h] = temp;}}}void print_array(int a[],int len){for (int i = 0; i < len; i++){cout << a[i] << " ";}    cout << endl;}int main(){int a[] = { 7,3,5,8,9,1,2,4,6 };cout << "before shell sort: ";print_array(a, 9);shell_sort(a, 9);cout << "after shell sort: ";print_array(a, 9);return 0;}


before shell sort: 7 3 5 8 9 1 2 4 6
after shell sort: 1 2 3 4 5 6 7 8 9




3.冒泡排序

//3.冒泡排序#include<iostream>using namespace std;void bubble_sort(int a[], int len){int i = 0;int j = 0;int temp = 0;for (i = 0; i < len - 1; i++){for (j = len - 1; j >= i; j--){if (a[j] < a[j-1]){temp = a[j-1];a[j-1] = a[j];a[j] = temp;}}}}void print_array(int a[], int len){for (int i = 0; i < len; i++){cout << a[i] << " ";}cout << endl;}int main(){int a[] = { 7,3,5,8,9,1,2,4,6 };cout << "before bubble sort: ";print_array(a, 9);bubble_sort(a, 9);cout << "after bubble sort: ";print_array(a, 9);return 0;}

before bubble sort: 7 3 5 8 9 1 2 4 6
after bubble sort: 1 2 3 4 5 6 7 8 9




4.快速排序

//4.快速排序#include<iostream>using namespace std;void quick_sort(int a[], int low, int high){int i, j, pivot;if(low<high){ pivot = a[low];i = low;j = high;while (i < j){while (i < j && a[j] >= pivot){j--;}if (i < j)   //a[j]<pivota[i++] = a[j];  //将比pivot小的元素移到低端while (i<j && a[i]<=pivot){i++;}if (i < j){a[j--] = a[i];}}a[i] = pivot;quick_sort(a, low,i - 1);quick_sort(a, i + 1, high);   }}int main(){int data[9] = { 54,38,96,23,15,72,60,45,83 };cout << "before quick sort: ";for (int i = 0; i < 9; i++)cout << data[i] << " ";cout << endl;cout << "after quick sort: ";quick_sort(data, 0, 8);for (int i = 0; i < 9; i++)cout << data[i] << " ";cout << endl;return 0;}

before quick sort: 54 38 96 23 15 72 60 45 83
after quick sort: 15 23 38 45 54 60 72 83 96