排序算法2——冒泡排序,快速排序
冒泡排序:
#include <iostream> using namespace std; void bubblesort(int *arry, int size) { for (int i = 0; i < size; i++) for (int j = i ; j < size;j++) if (arry[i]>arry[j ]) { int temp = arry[i]; arry[i] = arry[j]; arry[j] = temp; } } void print(int *arry, int size) { for (int i = 0; i < size; i++) cout << arry[i]; cout << endl; } void main() { int arry[5] = { 2, 3, 1, 4, 5 }; print(arry, 5); bubblesort(arry, 5); print(arry, 5); system("pause"); }
递增:
第一排序,放到数组第一位的一定是最小的,以此类推
理由:每一次交换都是把较小的那个放到了第一位,全部比较后,第一位就是最小的
快速排序:
#include <iostream> using namespace std; void quicksort(int *arry, int left, int right) { if (left < right) { int i = left; int j = right + 1; int temp; int flag = arry[left]; do{ do i++; while (arry[i] <= flag); do j--; while (arry[j] >= flag); if (i < j) { temp = arry[i]; arry[i] = arry[j]; arry[j] = temp; } } while (i < j); temp = arry[left]; arry[left] = arry[j]; arry[j] = temp; quicksort(arry, left, j - 1); quicksort(arry, j+1 , right); } } void print(int *arry, int size) { for (int i = 0; i < size; i++) cout << arry[i]; cout << endl; } void main() { int arry[5] = { 2, 1, 4, 3, 5 }; print(arry, 5); quicksort(arry, 0, 4); print(arry, 5); system("pause"); }