一、選擇排序算法
(1)、算法思想:依次是下標爲(0,1,2,....n)的數字和其後的全部數字進行比較,每一輪的比較結果:都先肯定最前面的是最小的數字;ide
(2)、代碼實現spa
#include<stdio.h> void sort(int *a, int count); void showArray(int *a, int count); void showArray(int *a, int count){ int i; for(i = 0; i < count; i++){ printf("%d ", a[i]); } printf("\n"); } void sort(int *a, int count){ int i; int j; int tmp; for(i = 0; i < count; i++){ for(j = i+1; j < count; j++){ if(a[i] > a[j]){ tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } } } void main(void){ int a[] = {3 ,5 ,6, 1, 7, 2, 9, 8}; int count = sizeof(a)/sizeof(int); sort(a, count); showArray(a, count); }
(3)、結果打印3d
(4)、算法分析blog
時間複雜度爲:O(n^2);排序
二、交換(冒泡)排序get
(1)、算法思想:相鄰的2個數字,兩兩進行比較,每一輪的排序結果:最大的數字在最後面的位置;
it
(2)、代碼實現io
#include<stdio.h> void swapSort(int *a, int count); void showArray(int *a, int count); void showArray(int *a, int count){ int i; for(i = 0; i < count; i++){ printf("%d ", a[i]); } printf("\n"); } void swapSort(int *a, int count){ int i; int j; int tmp; for(i = 0; i < count; i++){ for(j = 0; j < count-i; j++){ if(a[j] > a[j+1]){ //將大的數字放在最後面 tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } } } } void main(void){ int a[] = {3, 5, 7, 9, 1, 6, 10}; int count = sizeof(a)/sizeof(int); swapSort(a, count); showArray(a, count); }
(3)、結果截圖class
(4)、算法分析
時間複雜度:O(n^2);