整数排序的几种方法
Posted 南云之苑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了整数排序的几种方法相关的知识,希望对你有一定的参考价值。
网上看到有一位大神总结的代码,先记录如下:
````
class Solution {
public:
/*
* @param A: an integer array
* @return:
*/
void sortIntegers(vector
private:
// Quick sort
int partition(vector
int pivot = a[(left + right) / 2];
while (left <= right) {
// find the date at left side shift to right side
while (left<=right && a[left]<pivot)
left++;
// find the data at right side shift to left side
while (left<=right && a[right]>pivot)
right--;
// swap
if (left <= right) {
swap(a, left, right);
left++;
right--;
}
}
return left;
}
void Qsort(vector<int> &a, int left, int right) {
if (left<0 || right<=0 || left>=right)
return;
int index = partition(a, left, right);
if (left < index-1)
Qsort(a, left, index-1);
if (index < right)
Qsort(a, index, right);
}
void quickSort(vector<int> &a) {
if (a.size() <= 1)
return;
Qsort(a, 0, a.size() - 1);
}
// Insertion Sort
void insertionSort(vector<int> &a) {
for (int which=1; which < a.size(); which++) {
int val = a[which];
for (int i = 0; i < which; i++) {
if (a[i] > val) {
// do shift to
for (int j=which; j>i; j--) {
a[j] = a[j-1];
}
a[i] = val;
break;
}
}
}
}
// Selection sort
void swap(vector<int> &a, int index1, int index2) {
if (index1 == index2)
return;
auto it = a.begin();
int temp = *(it + index1);
*(it + index1) = *(it + index2);
*(it + index2) = temp;
}
int findSmallest(vector<int> &a, int start, int end) {
int min = start;
for (int i = start + 1; i <= end; i++) {
if (a[i] < a[min])
min = i;
}
return min;
}
void selectionSort1(vector<int> &a, int start, int end) {
if (start < end - 1) {
swap(a, start, findSmallest(a, start, end));
selectionSort1(a, start + 1, end);
}
}
void selectionSort1(vector<int> &a) {
if (a.size() <= 1)
return;
selectionSort1(a, 0, a.size() - 1);
}
// Selection sort
void selectionSort(vector<int> &a) {
if (a.size() <= 1)
return;
for (int i = 0; i < a.size() - 1; i++) {
int min = i;
for (int j = i+1; j < a.size(); j++) {
if (a[j] < a[min])
min = j;
}
if (min != i) {
auto it = a.begin();
int temp = *(it + min);
*(it + min) = *(it + i);
*(it + i) = temp;
}
}
}
// buble sort
void bubleSort(vector<int> &a) {
if (a.size() <=1)
return;
for (int i = 0; i < a.size(); i++) {
for (int j = 1; j < a.size() - i; j++) {
if (a[j] < a[j - 1]) {
auto it = a.begin();
int temp = *(it + j);
*(it + j) = *(it + j - 1);
*(it + j - 1) = temp;
}
}
}
}
};
```
以上是关于整数排序的几种方法的主要内容,如果未能解决你的问题,请参考以下文章