冒泡排序
void BubbleSort(int arr[],int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - 1 - i; j++)
{
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
选择排序
void SelectSort(int arr[], int len)
{
for (int i = 0; i < len - 1; i++)
{
int min = i;
for (int j = i + 1; j < len; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
快速排序
void QuickSort(int arr[], int begin, int end)
{
if (begin > end)
{
return;
}
int temp = arr[begin];
int i = begin, j = end;
while (i != j)
{
while (arr[j] >= temp && j > i)
{
j--;
}
while (arr[i] <= temp && j > i)
{
i++;
}
if (j > i)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
arr[begin] = arr[i];
arr[i] = temp;
QuickSort(arr, begin, i - 1);
QuickSort(arr, i + 1, end);
}
希尔排序:
void ShellInsert(vector<int>&s, int gap)
{
for (int i = gap; i < s.size(); i++)
{
for (int j = i-gap; j >=0 ; j-=gap)
{
if (s[j] > s[j + gap])
{
int temp = s[j + gap];
s[j + gap] = s[j];
s[j] = temp;
}
else
{
break;
}
}
}
}
堆排序
void adjust(int arr[], int len, int index)
{
int left = 2 * index + 1;
int right = 2 * index + 2;
int maxindex = index;
if (left < len && arr[left] > arr[maxindex])
{
maxindex = left;
}
if (right < len && arr[right] > arr[maxindex])
{
maxindex = right;
}
if (maxindex != index)
{
swap(arr[maxindex], arr[index]);
adjust(arr, len, maxindex);
}
}
void HeapSort(int arr[], int size)
{
for (int i = size/2 - 1; i >=0; i--)
{
adjust(arr, size, i);
}
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
for (int i = size - 1; i >= 1; i--)
{
swap(arr[0], arr[i]);
adjust(arr, i, 0);
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
}