整数排序的几种方法
网上看到有一位大神总结的代码,先记录如下:
class Solution {
public:
/*
* @param A: an integer array
* @return:
*/
void sortIntegers(vector<int> &A) {
// write your code here
//bubleSort(A);
//selectionSort(A);
//selectionSort1(A);
//insertionSort(A);
quickSort(A);
}
private:
// Quick sort
int partition(vector<int> &a, int left, int right) {
if (left<0 || right<=0 || left>=right)
return -1;
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;
}
}
}
}
};
作者:YunLambert
-------------------------------------------
个性签名:一名会音乐、爱健身的不合格程序员
可以Follow博主的Github哦(っ•̀ω•́)っ✎⁾⁾