优化代码:以升序为例,给是否发生交换打标记,没有发生交换则直接结束
void bubbleSort(int* arr,int size)
{
for (int i = 0; i < size - 1; i++)
{
int flag = 1;
for (int j = 0; j < size - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
flag = 0;
}
}
if (flag)
break;
}
}
代码:以升序为例
void insertSort(int* arr, int size)
{
for (int i = 1; i < size; i++)
{
int j = i,temp = arr[i];
while (j > 0 && temp < arr[j-1])
{
arr[j] = arr[j - 1];
j--;
}
arr[j] = temp;
}
}
优化代码:利用二分查找来优化时间效率,但只对特大数据量有一定效果(因为没有对遍历时间优化,只优化了查找时间)
int binarySearch(int* arr, int left, int right, int target)
{
while (left <= right)
{
int mid = (left + right) / 2;
if (target == arr[mid])
return mid + 1;
else if (target > arr[mid])
left = mid + 1;
else
right = mid - 1;
}
return left;
}
void insertSort(int* arr, int size)
{
for (int i = 1; i < size; i++)
{
int j = binarySearch(arr, 0, i - 1, arr[i]), temp = arr[i];
for (int k = i; k > j; k--)
arr[k] = arr[k - 1];
arr[j] = temp;
}
}
代码:以升序为例,效率很低
void selectSort(int* arr, int size)
{
for (int i = 0; i < size; i++)
{
int min = i;
for (int j = i+1; j < size; j++)
{
if (arr[j] < arr[min])
min = j;
}
swap(arr[i], arr[min]);
}
}
优化代码:每次同时找最大、最小值,效率节省一半,但还是慢
void selectSort(int* arr, int size)
{
int left = 0, right = size - 1;
while(left<=right)
{
int min = left,max = right;
for (int i = left; i <= right; i++)
{
if (arr[min] > arr[i])
min = i;
if (arr[max] < arr[i])
max = i;
}
swap(arr[left++], arr[min]);
if (arr[min] > arr[max])
max = min;
swap(arr[right--], arr[max]);
}
}
这三种基本排序算法的复杂度如下:
代码:以升序为例
void quickSort(int arr[], int start, int end)
{
if (start >= end)
return;
int left = start, right = end,pivot = arr[left];
while (left < right)
{
while (left < right && pivot <= arr[right])
right--;
arr[left] = arr[right];
while (left < right && pivot >= arr[left])
left++;
arr[right] = arr[left];
}
arr[left] = pivot;
quickSort(arr, start, left - 1);
quickSort(arr, left + 1, end);
}
代码:快速排序的进阶,在处理大数据数组时效率高
void dualPivotQuickSort(int arr[], int start, int end) {
if (start >= end) return;
if (arr[start] > arr[end])
swap(arr[start], arr[end]);
int pivot1 = arr[start], pivot2 = arr[end];
int left = start, right = end, mid = left + 1;
while (mid < right) {
if (arr[mid] < pivot1)
swap(arr[++left], arr[mid++]);
else if (arr[mid] <= pivot2) {
mid++;
}
else {
while (arr[--right] > pivot2 && right > mid);
if (mid >= right) break;
swap(arr[mid], arr[right]);
}
}
swap(arr[start], arr[left]);
swap(arr[end], arr[right]);
dualPivotQuickSort(arr, start, left - 1);
dualPivotQuickSort(arr, left + 1, right - 1);
dualPivotQuickSort(arr, right + 1, end);
}
代码:插入排序的进阶版
void shellSort(int* arr, int size)
{
int step = size / 2;
while (step >= 1)
{
for (int i = step; i < size; i++)
{
int j = i, tmp = arr[i];
while (j > 0 && tmp < arr[j - step])
{
arr[j] = arr[j - step];
j -= step;
}
arr[j] = tmp;
}
step = step / 2;
}
}