1,冒泡排序
//1.排序
int a[5] = {5,4,7,1,0};
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5-i -1; j++) {
if (a[j]< a[j+1]) {
int temp = 0;
temp= a[j];
a[j] = a[j +1];
a[j+1] = temp;
}
}
}
//2.打印
for (int i = 0; i < 5; i++) {
printf(“%d\t”,a[i]);
}
2.(水桶排序法)浪费空间效率,提高时间效率
int a[] = {2,7,5,5,9,0,1,15};
//数组元素个数
int count = sizeof(a)/sizeof(int);
//最大值,最小值
int min = a[0],max = a[0];
for (int i = 0; i < count; i++) {
if (min>a[i]) {
min = a[i];
}
if (max<a[i]) {
max = a[i];
}
}
printf(“min:%d,max:%d\n”,min,max);
//水桶个数
int shuitongCount = max - min + 1;
printf(“水桶个数:%d\n”,shuitongCount);
//为数组开辟空间
int *b = malloc(4*shuitongCount);
for (int i = 0; i < count; i++) {
b[a[i]]++;
}
//打印数组元素
for (int i = 0; i < shuitongCount; i++) {
while (b[i]) {
printf(“%d\t”,i);
b[i]—;
}
}
printf(“\n”);
3.选择排序(每次都从待排序队列中找到最小的元素)
int a[6] = {2,7,5,5,9,0};
int count = sizeof(a)/sizeof(int);
int minIndex = 0;//下标
for (int i = 0 ; i < count; i++) {
minIndex= i;
for (int j = i + 1; j < count; j++) {
if (a[j] < a[minIndex]) {
minIndex = j;//记录下表
}
}
if (minIndex != i) {//交换
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
//打印
for (int i = 0; i < count; i++) {
printf(“%d\t”,a[i]);
}
printf(“\n”);
4.折半查找
int a[] = {4,5,9,78,89,626,957};
int count = sizeof(a)/sizeof(int);
int target = 9;
int start = 0;
int end = count-1;
int mid = (start + end)/2;
//只要start在end 的左边,就一直查找
while (start <= end) {
if (a[mid] < target) {
start = mid + 1;
}else if (a[mid]>target){
end = mid - 1;
}else{
break;
}
mid = (start + end) / 2;
}
if (start <= end) {
printf(“元素存在\n”);
}else{
printf(“元素不存在\n”);
}