快排:
#include <iostream> #include <string.h> #include <stdio.h> #include <cmath> using namespace std; void Q_Sort(int a[],int low,int high) { if(low >= high) return; int first = low; int last = high; int key = a[first]; while(first < last) { while(first < last && a[last] >= key) { last--; } a[first] = a[last]; while(first < last && a[first] <= key) { first++; } a[last] = a[first]; } a[first] = key; Q_Sort(a,low,last); Q_Sort(a,last+1,high); } int n = 9; int a[] = {57, 68, 59, 52, 72, 28, 96, 33, 24}; void print() { for(int i=0;i<n;i++) { printf("%d ",a[i]); } printf("\n"); } int main() { print(); Q_Sort(a,0,8); print(); return 0; }
快排:在当前要排序的数组中,选取一个数为基准,然后将数组分成两部分,一部分是比当前数小,另外一部分比此基准大,然后分治递归相同的操作,快排的最坏的时间复杂度是最坏时间为O(n2),平均时间复杂度是O(nlgn)。
归并排序:
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; #define maxn 1100 int mmap[maxn]; void Merge(int num[],int first,int mid,int last) { int i=first; int j = mid+1; int Index = 0; while(i<=mid && j <= last) { if(num[i] <= num[j]) { mmap[Index++] = num[i++]; } else { mmap[Index++] = num[j++]; } } while(i<=mid) { mmap[Index++] = num[i++]; } while(j <= last) { mmap[Index++] = num[j++]; } for(int m=0;m<Index;m++) { num[first++] = mmap[m]; } } void MergeSort(int num[],int first,int last) { if(first == last) { return; } int mid = (first + last)/2; MergeSort(num,first,mid); MergeSort(num,mid+1,last); Merge(num,first,mid,last); } int num[maxn]; int main() { int n; cin>>n; for(int i=0;i<n;i++) { cin>>num[i]; } MergeSort(num,0,n-1); for(int i=0;i<n;i++) { printf("%d ",num[i]); } printf("\n"); return 0; }
归并排序:是根据分治的思想,想将数据分成两段,然后以此递归,然后再合并
时间复杂度是:O(nlgn)
冒泡排序:
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; #define maxn 1100 int mmap[maxn]; int n; void Bubble_Sort() { int temp; bool flag; for(int i=0;i<n-1;i++) { flag = 0; for(int j=n-2;j>=i;j--) { if(mmap[j] > mmap[j+1]) { temp = mmap[j+1]; mmap[j+1] = mmap[j]; mmap[j] = temp; flag = 1; } } if(!flag) break; } } int main() { while(~scanf("%d",&n)) { for(int i=0;i<n;i++) { scanf("%d",&mmap[i]); } Bubble_Sort(); for(int i=0;i<n;i++) { printf("%d ",mmap[i]); } printf("\n"); } return 0; }
冒泡排序:将数组中的两个元素进行比较,然后找到最大的放到最后,然后以此来循环
时间复杂度是:O(n2)
时间: 2024-10-01 04:20:43