冒泡:
#include<iostream> #include<stdio.h> using namespace std; void sort(int* arr, int n) { int length; int i, j; int temp; length = n; for (i = 0; i < length; i++) { for (j = 0; j < length - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } int main() { int n; int i = 0; int arr[100]; cout << "输入数组元素个数:" << endl; cin >> n; cout << "\n输入数组:" << endl; for (i = 0; i < n; i++) { cin >> arr[i]; } cout << "\n输入的数组为:" << endl; for (i = 0; i < n; i++) { cout << arr[i] << " , "; } sort(arr, n); cout << "\n冒泡结果为:" << endl; for (i = 0; i < n; i++) { cout << arr[i] << " , "; } }
快排:
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; int quicksort(int *arr, int left, int right) { int mid; mid = arr[left]; while (left < right) { //从右边开始 while(left<right && arr[right]>mid) right--; arr[left] = arr[right]; while(left < right && arr[left] < mid) left++; arr[right] = arr[left]; } //此时left等于right arr[left] = mid; return left; } void sort(int *arr, int left, int right) { int pivot; pivot = arr[left]; if (left < right) { pivot = quicksort(arr, left, right); //选出支点 sort(arr, left, pivot - 1); //负责支点左边的快排 sort(arr, pivot + 1, right); //负责支点右边的快排 }
//等到所有排序的left=right了,就会跳出 } int main() { int n; int i = 0; int arr[100]; cout << "输入数组元素个数:" << endl; cin >> n; cout << "\n输入数组:" << endl; for (i = 0; i < n; i++) { cin >> arr[i]; } cout << "\n输入的数组为:" << endl; for (i = 0; i < n; i++) { cout << arr[i] << " , "; } sort(arr, 0, n - 1); cout << "快排结果为:" << endl; for (i = 0; i < n; i++) { cout << arr[i] << " , "; } }