歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 選擇排序Linux下C實現

選擇排序Linux下C實現

日期:2017/3/1 10:09:31   编辑:Linux編程
選擇排序,將待排序序列分為兩個序列:已排序序列和未排序序列。每次從未排序序列中,選擇一個最小的元素,存放在到已排序序列的最後,直到所有元素排序完畢。關鍵代碼如下:

1、選擇排序頭文件:selectSort.h

  1. #ifndef SELECTSORT_H
  2. #define SELECTSORT_H
  3. extern void selectSort(int *pArr, const int length);
  4. #endif
2、選擇排序源文件:selectSort.c
  1. #include "selectSort.h"
  2. void selectSort(int *pArr, const int length)
  3. {
  4. int i,j,min,tmp;
  5. for(i=0; i<length-1; i++)
  6. {
  7. min =i;
  8. for(j=i+1; j<length; j++)
  9. {
  10. if(*(pArr+min)>*(pArr+j))
  11. {
  12. min=j;
  13. }
  14. }
  15. if(min!=i)
  16. {
  17. tmp=*(pArr+i);
  18. *(pArr+i)=*(pArr+min);
  19. *(pArr+min)=tmp;
  20. }
  21. }
  22. }
3、main頭文件:main.h
  1. #ifndef MAIN_H
  2. #define MAIN_H
  3. #include<stdio.h>
  4. #include "selectSort.h"
  5. int main(void);
  6. void showArr(const int *pArr, const int length);
  7. void initRandomArr(int *pArr, const int length);
  8. #endif
4、main源文件:main.c
  1. #include "main.h"
  2. int main(void)
  3. {
  4. printf("Input array length:\n");
  5. int length;
  6. scanf("%d", &length);
  7. if(length<0)
  8. {
  9. printf("Array length must be larger 0\n");
  10. return 1;
  11. }
  12. int arr[length];
  13. initRandomArr(arr, length);
  14. printf("Get random array :\n");
  15. showArr(arr, length);
  16. selectSort(arr, length);
  17. printf("select sort result:\n");
  18. showArr(arr, length);
  19. return 0;
  20. }
  21. void showArr(const int *pArr, const int length)
  22. {
  23. int i;
  24. for(i=0; i<length; i++)
  25. {
  26. printf("%d ", *(pArr+i));
  27. }
  28. printf("\n");
  29. }
  30. void initRandomArr(int *pArr, const int length)
  31. {
  32. int i;
  33. srand(time(NULL));
  34. for(i=0; i< length; i++)
  35. {
  36. *(pArr+i)=rand()%1000;
  37. }
  38. }
5、編譯程序:
  1. [root@localhost selectSort]$ gcc -c main.c
  2. [root@localhost selectSort]$ gcc -c selectSort.c
  3. [root@localhost selectSort]$ gcc -o main main.o selectSort.o
執行可執行文件main,大致如下:
  1. [root@localhost selectSort]$ ./main
  2. Input array length:
  3. 8
  4. Get random array :
  5. 906 968 161 208 757 885 370 691
  6. select sort result:
  7. 161 208 370 691 757 885 906 968
選擇排序時間復雜度О(n²), 交換次數O(n),已經有序的最好情況下,交換0次;逆序的最壞情況下,交換n-1次。 交換次數比冒泡排序少多了,由於交換所需CPU時間比比較所需的CPU時間多,n值較小時,選擇排序比冒泡排序快 http://www.linuxidc.com/Linux/2012-03/55662.htm。
Copyright © Linux教程網 All Rights Reserved