比较慢:
冒泡排序:
列表每两个相邻的数,如果前⾯⽐后⾯⼤,则交换这两个数。
⼀趟排序完成后,则⽆序区减少⼀个数,有序区增加⼀个数。
代码关键点:趟、⽆序区范围
#include "stdio.h"
int main(){
int arr[] = {8, 32, 22, 73, 95, 13, 9, 82, 23, 46, 71, 52, 90, 53, 77, 75, 65, 64, 74, 24};
int n = sizeof (arr) / sizeof (arr[0]);
int i, j;
for(i = 0; i < n; i++){
for(j = 0; j < n - i - 1; j ++){
if(arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Output:\n");
for(int k = 0; k < n; k++){
printf("%d ", arr[k]);
}
return 0;
}
选择排序:
选择最小的数
#include "stdio.h"
int main(){
int arr[] = {8, 32, 22, 73, 95, 13, 9, 82, 23, 46, 71, 52, 90, 53, 77, 75, 65, 64, 74, 24};
int n = sizeof (arr) / sizeof (arr[0]);
int i, j;
for(i = 0; i < n - 1; i++){
for(j = i; j < n; j++){
if(arr[j] < arr[i]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("Output:\n");
for(int k = 0; k < n; k++){
printf("%d ", arr[k]);
}
return 0;
}
插入排序:
初始时⼿⾥(有序区)只有⼀张牌
每次(从⽆序区)摸⼀张牌,插⼊到⼿⾥已
有牌的正确位置
#include "stdio.h"
int main(){
int i, j, temp;
int arr[] = {8, 32, 22, 73, 95, 13, 9, 82, 23, 46, 71, 52, 90, 53, 77, 75, 65, 64, 74, 24};
int n = sizeof (arr) / sizeof (arr[0]);
//表示摸到的牌的下标
for(i = 1; i < n; i++){
temp = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > temp){
//大的后移
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = temp;
}
for(int k = 0; k < n; k++){
printf("%d ", arr[k]);
}
return 0;
}
标签:arr,temp,int,++,算法,冒泡,printf,sizeof,排序
From: https://blog.51cto.com/u_16172166/9204298