快速排序是面试中最重要的排序。面试官常用这个来考别人,虽然本人鄙视(这个在工作中根本用不到,说实话,真的用这个来筛选别人,有意义吗?),一方面为了面试,一方面觉得快速排序还是挺巧妙的,不过本人更喜欢推排序,以上纯属一个无聊人的牢骚,勿介。
快速排序:
#include<stdio.h>
#include <conio.h>
void quickSort(int array[], int low, int high);
int getIndex(int array[], int low, int high);
int main()
{
int vec[10] = { 2,9,5,8,2,4,8,6,5,10}
printf(“排序前的vec: “);
for (int i = 0; i < 10; i++)
{
printf(”%d “, vec[i]);
}
printf(”\n”);
quickSort(vec, 0, 9);
printf("排序后的vec: “);
for (int i = 0; i < 10; i++)
{
printf(”%d ", vec[i]);
}
_getch(); //控制台停留
return 0;
}
void quickSort(int array[], int low, int high)
{
if (low < high)
{
int index = getIndex(array, low, high);
quickSort(array, low, index - 1);
quickSort(array, index+1, high);
}
}
int getIndex(int array[],int low,int high)
{
int indexData = array[low]; //基底
while (low < high)
{
while (low<high && array[high]>=indexData) //理解等号比较重要
{
high–;
}
array[low] = array[high];
while (low < high && array[low] <= array[high])//理解等号比较重要,因为是从low开始的
{
low++;
}
array[high] = array[low];
}
//需要理解,最后low和high会相等,找到分割的索引。
array[low] = indexData;
return low; //low和high最后相等
}
冒泡排序
void bubblingSort(int array[], int len);
int main()
{
int vec[10] = { 2,9,5,8,2,4,8,6,5,10};
printf(“排序前的vec: “);
for (int i = 0; i < 10; i++)
{
printf(”%d “, vec[i]);
}
printf(”\n”);
bubblingSort(vec, 10);
printf("排序后的vec: “);
for (int i = 0; i < 10; i++)
{
printf(”%d ", vec[i]);
}
_getch();
return 0;
}
void bubblingSort(int array[], int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = i + 1; j < len; j++)
{
if (array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}