如有补充/优化 欢迎各路大神指点一二三四五六七......
本小菜刚踏入IT这个深坑
针对前段时间学习有关C语言的数组部分知识自己总结了一下
同时反复敲,适合练手热身
冒泡排序
//此算法是对普通冒泡算法的优化,解决了特殊情况(当中途排序,出现后面的数刚好排完,而前面的数也已经排完,数组提前完成排序)下,避免代码重复运行,提高效率。
int array[] = {3, 5, 7, 2, 1, 9, 8, 6, 4};
int count = sizeof(array) / sizeof(array[0]);
int flag = 0;
//flag 为有序标志 0为无序 1为有序 为防止后面的数排完,前面也刚好排完,数组提前完成排序而引用该标志
for (int i = 0; i < count -1 && flag ==0; i++) {
flag = 1;
for (int j = 0; j < count - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
flag = 0;
}
}
}
for (int i = 0; i < count; i++) {
printf("%d\n", array[i]);
}
选择排序
int array[] = {1, 5, 3, 6, 8, 2, 4, 9, 7};
int count = sizeof(array) / sizeof(array[0]);
for (int i = 0; i < count - 1; i++) {
int minIndex = i;
for (int j = minIndex + 1; j < count; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = 0;
temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < count; i++) {
printf("[%2d] : %d\n", i, array[i]);
}
插入排序
int array[] = {3, 5, 8, 2, 4, 9, 7, 1, 6};
int count = sizeof(array) / sizeof(array[0]);
for (int i = 1; i < count; i++) {
int j = i;
int temp = array[j];
while (j > 0 && temp < array[j - 1]) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
}
for (int i = 0; i < count; i++) {
printf("[%d] : %d\n", i, array[i]);
}
索引数组进行排序(模拟数据库的索引文件)
int array[] = {1, 3, 6, 12, 4, 15, 14, 5, 7, 8};
int brray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int count = sizeof(array) / sizeof(array[0]);
for (int i = 0; i < count; i++) {
int minIndex = i;
for (int j = minIndex + 1; j < count; j++) {
if (array[brray[minIndex]] > array[brray[j]]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = brray[i];
brray[i] = brray[minIndex];
brray[minIndex] = temp;
}
}
for (int i = 0; i < count; i++) {
printf("%d \n", brray[i]);
}
折半查找
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int count = sizeof(array) / sizeof(array[0]);
int target = 9;
int start = 0, end = count - 1, mid = (start + end) / 2;
while (start <= end) {
mid = (start + end) / 2;
if (array[mid] < target) {
start = mid + 1;
}
else if (array[mid] > target){
end = mid - 1;
} else {
break;
}
}
if (start <= end) {
printf("[%d] : %d\n", mid, array[mid]);
}else{
printf("not found");
}
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int count = sizeof(array) / sizeof(array[0]);
for (int i = count - 1; i > 0; i--) {
int rIndex = arc4random() % (i + 1);
if (rIndex != i) {
int temp;
temp = array[rIndex];
array[rIndex] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < count; i++) {
printf("[%d] : %d\n", i, array[i]);
}