冒泡排序
效率低,但是稳定性高
代码
// 冒泡排序
void maopao(int a[]);int main()
{int a1[10] = {34,78,29,46,12,85,63,92,57,31};printf("\n排序前:\n");print(a1);maopao(a2);printf("冒泡排序后:");print(a2);
}//冒泡排序
void maopao(int a[])
{for(int i = 0; i < 10; i++){for(int j = 0; j < 10-i-1; j++){if(a[j] > a[j+1]){swap(&a[j], &a[j+1]);}}}
}
快速排序(霍尔法)
效率更高,但是稳定性差
代码
// 打印数组
void print(int a[]);
// 元素交换
void swap(int *a, int *b);
// 快速排序
void kuaisu(int *left, int *right);int main()
{int a1[10] = {34,78,29,46,12,85,63,92,57,31};int a2[10] = {34,78,29,46,12,85,63,92,57,31};printf("\n排序前:\n");print(a1);kuaisu(a1, a1+9);printf("快速排序后:");print(a1);
}// 打印数组
void print(int a[])
{for(int i = 0; i < 10; i++){printf("%d ", a[i]);}printf("\n");
}
// 交换两个元素
void swap(int *a, int *b)
{int temp = *a;*a = *b;*b = temp;
}// 快速排序
void kuaisu(int *left, int *right)
{if(left >= right)return;int *i = left;int *j = right;while( i < j ){while(i < j && *j >= *left)j--;while(i < j && *i <= *left)i++;if(i < j)swap(i, j);}swap(i,left);kuaisu(left, i-1);kuaisu(i+1, right);return;
}