排序算法小记

xiaoxiao2021-02-27  273

#include <stdio.h> //冒泡排序,适合于数据量较小的情况,效率较低(最好的时间复杂度为O(n),最坏时间复杂度为O(n*n),平均时间复杂度为O(n*n)) void bubble_sort(int a[], int len) { int j, i, temp; for (i = 0; i < len - 1; i++) { for (j = 0; j < len - 1 - i; j++) { if(a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } } //交换排序 void swapsort(int a[],int length) { for(int i = 0; i < length-1; i++) { for(int j = i+1; j < length; j++) { if(a[j] < a[i]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } //快速排序 void QuickSort(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;/*枢轴记录到位*/ QuickSort(a, low, first-1); QuickSort(a, first+1, high); } int main() { int number[8] = {95, 45, 15, 78, 84, 51, 24, 12}; int len = sizeof(number)/sizeof(int); bubble_sort(number, len); for (int i = 0; i < len; i++) { printf("%d ", number[i]); } printf("\n"); return 0; }
转载请注明原文地址: https://www.6miu.com/read-2628.html

最新回复(0)