冒泡排序,取舍排序,希尔排序
冒泡排序,选择排序,希尔排序
#include <stdlib.h> #include <stdio.h> /* 冒泡排序 */ int BubbleSort(int a[],int n) { int i,j,temp,exchanged=0,cycles=0; for(i=0; i<n; i++) { exchanged = 0; for(j=n-1; j>i; j--) { if(a[j] < a[j-1])//交换相邻元素 { temp = a[j] ; a[j] = a[j-1]; a[j-1] = temp; exchanged = 1; } cycles++; } if(0 == exchanged)break; } return cycles; } /* 选择排序 */ void SelectSort(int array[], int n) { int i,j,t; for (i=0;i<n-1;i++) { int pos = i; for (j=i+1;j<n;j++) { if (array[j]<array[pos]) { pos = j;//只是找到位置,并不需要每次都换一下 } } //找到位置后才交换,不是交换相邻元素,而是把最小的元素放在s[j]中 t = array[i]; array[i] = array[pos]; array[pos] = t; } } /* 希尔排序 */ void ShellInsert(int a[], int n, int d) { int i,temp,j,cycles=0; for(i=d; i<n; i++) { if(a[i] < a[i-d])//需要移动 { temp = a[i]; for(j=i-d; j>=0 && a[j]>temp; j-=d) a[j+d] = a[j];//后移 a[j+d] = temp; } } } void ShellSort(int a[], int n, int dist[],int k) { int i; for(i=0; i<k; i++)//间距 ShellInsert(a,n,dist[i]); } int main(int argc, char *argv[]) { int a[] = {4,5,3,2,9,8,1,7,6,0}; int b[] = {0,1,2,3,4,5,6,7,8,9}; int c[] = {9,8,7,6,5,4,3,2,1,0}; int dist[] = {5,3,2,1}; int i; ShellSort(c,10,dist,4); //printf("%d cycles\n",i); for(i=0; i<10; i++)printf("%d\t",c[i]); printf("\n"); return 1; }
- 2楼jschen10昨天 18:33
- 第57行错了,应为a[j+d] = temp
- Re: CreazyApple昨天 22:11
- 回复jschen10n是呢!谢谢您!看的好仔细阿!
- 1楼q599057400昨天 16:06
- 是啥?