很久很久以前,曾經寫了篇文章:冒泡排序 Linux下C 實現 ,這次再show個冒泡排序的變種:雞尾酒排序。 雞尾酒排序在排序時,從兩個方向在序列中排序。先找到最大的數字放到最後一位,然後找到最小的數字,放到第一位;然後再找到第二大的數字放到倒數第二位,再找到第二小的數字放到第二位。以此類推,直到完成排序。詳細實現,請參閱下面的關鍵代碼:
1、排序頭文件:cocktailSort.h
- #ifndef COCKTAILSORT_H
- #define COCKTAILSORT_H
- #include<stdbool.h>
- extern void cocktailSort(int * pArr, int length);
- #endif
2、排序源文件:cocktailSort.c
- #include "cocktailSort.h"
- void cocktailSort(int * pArr, int length)
- {
- int bottom = 0;
- int top = length-1;
- bool swapped = true;
- int tmp,i;
- while(swapped)
- {
- swapped = false;
- for(i=bottom; i<top; i++)
- {
- if(*(pArr+i)>*(pArr+i+1))
- {
- swapped =true;
- tmp = *(pArr+i);
- *(pArr+i)=*(pArr+i+1);
- *(pArr+i+1)=tmp;
- }
- }
- top--;
- for(i=top; i>bottom; i--)
- {
- if(*(pArr+i)<*(pArr+i-1))
- {
- swapped = true;
- tmp = *(pArr+i);
- *(pArr+i)=*(pArr+i-1);
- *(pArr+i-1)=tmp;
- }
- }
- bottom++;
- }
- }
3、main函數頭文件:main.h
- #ifndef MAIN_H
- #define MAIN_H
- #include<stdio.h>
- #include "cocktailSort.h"
- extern void outputArr(const int *pArr, int lenght);
- extern int main(void);
- #endif
3、main函數源文件:main.c
- #include "main.h"
- int main(void)
- {
- printf("input array length:\n");
- int length;
- scanf("%d", &length);
- if(length<0)
- {
- printf("array length must be larger 0\n");
- return 1;
- }
- printf("array lenght is %d \n", length);
-
- int arr[length];// ={1, 3, 6,5, 4};
- int i=0;
- for(i=0;i<length;i++)
- {
- printf("input arr[%d] value\n",i);
- scanf("%d", &arr[i]);
- }
-
- printf("orig array:");
- outputArr(arr, length);
- cocktailSort(arr,length);
-
- printf("cocktail sort array:");
- outputArr(arr, length);
- return 0;
- }
- void outputArr(const int *pArr, int length)
- {
- int i;
- for(i=0;i<length;i++)
- {
- printf(" %d",*(pArr+i));
- }
- printf("\n");
- }
4、Makefile文件:Makefile
- all: main
- main: main.o cocktailSort.o
- gcc -o main main.o cocktailSort.o
- main.o: main.c cocktailSort.c cocktailSort.h
- gcc -c main.c
- cocktailSort.o: cocktailSort.c cocktailSort.h
- gcc -c cocktailSort.c
- clean:
- @echo "start cleaning"
- -rm main *.o
- @echo "clean completed"
- .PHONY: clean
5、編譯
- make
如果不出意外,可以看到可執行文件main。然後執行可執行文件,如下所示:
- [root@localhost sort]$ ./main
- input array length:
- 5
- array lenght is 5
- input arr[0] value
- 34
- input arr[1] value
- 67
- input arr[2] value
- 89
- input arr[3] value
- 4
- input arr[4] value
- 3
- orig array: 34 67 89 4 3
- cocktail sort array: 3 4 34 67 89