排序
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<time.h>
void Swap(int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
void Init_Ar(int* ar, int n)
{
assert(ar != nullptr);
srand((size_t)time(nullptr));
for (int i = 0; i < n; ++i)
{
ar[i] = rand() % 100 + 1;
}
}
void Print_Ar(int* ar, int n)
{
assert(ar != nullptr);
for (int i = 0; i < n; ++i)
{
printf("%4d", ar[i]);
}
printf("\n");
}
void BubbleSort(int* ar, int n)
{
assert(ar != nullptr);
for (int i = 0; i < n - 1; ++i) //up->down
{
bool tag = true; //设置标记,尽量减少循环次数,使时间复杂度变小
for (int j = 0; j < n - 1 - i; ++j)
{
if (ar[j] > ar[j + 1])
{
Swap(ar[j], ar[j + 1]);
tag = false;
}
}
if (tag) break;
tag = true;
for (int j = n - 2 - i; j > i; --j) //dowm->up,在一趟循坏里找出最大的和最小的;
{
if(ar[j]<ar[j-1])
{
Swap(ar[j], ar[j - 1]);
tag = false;
}
}
if (tag) break;
}
}
void InsertSort(int* ar, int n)
{
assert(ar != nullptr);
for (int i = 1; i < n; ++i)
{
if (ar[i] < ar[i - 1])
{
int j = i - 1;
int tmp = ar[i];
do
{
ar[i] = ar[i - 1];
j--;
} while (ar[j] > tmp && j >= 0);
ar[j+1] = tmp;
}
}
}
int Parition(int* ar, int left, int right)
{
assert(ar != nullptr);
int tmp = ar[left];
while (left < right)
{
while (left < right && tmp < ar[right])
{
right--;
}
if (left < right)ar[left] = ar[right];
while (left < right && tmp >= ar[left])
{
left++;
}
if (left < right)ar[right] = ar[left];
}
ar[left] = tmp;
return left;
}
void QuickPass(int* ar, int left, int right)
{
assert(ar != nullptr);
if (left < right)
{
int pos = Parition(ar, left, right);
QuickPass(ar, 0, pos - 1);
QuickPass(ar, pos + 1, right);
}
}
void QuickSort(int* ar, int n)
{
assert(ar != nullptr);
QuickPass(ar, 0, n - 1);
}
int main()
{
const int n = 10;
int ar[n] = { 0 };
Init_Ar(ar, n);
Print_Ar(ar, n);
//BubbleSort(ar, n);
//InsertSort(ar, n);
QuickSort(ar, n);
Print_Ar(ar, n);
return 0;
}
大家可以自己写完冒泡,再写一下选择排序,提示一下,选择排序是移动数组的下标哈–…--