选择排序 从 index = 0 开始,初始化最小值的索引为:0;
class Solution
{
public:
void SelectionSort(vector<int> vector)
{
int len = vector.size();
int MinIndex, temp;
for(int i = 0; i < len-1; i++) // n个数,范围 [0, n-2]末尾要留一个数
{
MinIndex = i;
for(int j = i+1; j < len; j++) //留一个数的意义在此,为了j
{
if(vector[j] < vector[MinIndex]) //若j < MinIndex
{
MinIndex = j; //只是交换索引
}
} //i之后的所有数都参与了比较,
temp = vector[i]; //开始更新值
vector[i] = vector[MinIndex];
vector[MinIndex] = temp;
}
return vector;
}
};
此下python的代码 已在Jupyter上实际操作
def Selection_sort(list01):
for i in range(len(list01)-1):
min_index = i
for j in range(i + 1,len(list01)):
if list01[j] < list01[min_index]:
min_index = j
list01[min_index], list01[i] = list01[i], list01[min_index]
return list01
################################################
快速排序:S数组, N个数
以左侧第一个值为界点。
起始:左侧从索引 0 开始, 右侧以索引N-1开始
先从右侧开始,r–,寻找小于界点的值,找到停止,
再从左侧开始,l++,寻找大于界点的值,找到停止,
若此时 r < j,则交换二者
否则,【r ≥ j】,则将界点数,与 j 对应的数进行交换。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
void QSort(vector<int> &vec, int low, int high)
{
int pivoteLoc;
if (low < high)
{
pivoteLoc = Partition(vec, low, high);
QSort(vec, low, pivoteLoc - 1);
QSort(vec, pivoteLoc + 1, high);
}
}
private:
int Partition(vector<int> & SubVec, int low, int high)
{
int temp = SubVec[low];
int pivotKey = SubVec[low];
while (low <high)
{
while (low < high && SubVec[high] >= pivotKey)
{
high--;
}
SubVec[low] = SubVec[high];
while (low < high && SubVec[low] <= pivotKey)
{
low++;
}
SubVec[high] = SubVec[low];
}
SubVec[low] = pivotKey;
return low;
}
};
void display(vector<int> vec)
{
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
}
int main()
{
vector<int> vec = { 72, 6, 57, 88, 60, 42, 83, 73, 48, 85,101, 2, 7, 78, 8 };
cout << endl;
display(vec);
cout << "***************************" << endl;
Solution s;
s.QSort(vec, 0, 14);
display(vec);
system("pause");
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
void QSort(vector<int>& vec, int l, int r)
{
if (l >= r)
{
return;
}
int low = l;
int high = r;
//int pivot;
int pivoteKey = vec[l];
while (low < high)
{
while (vec[high] >= pivoteKey && low < high)
{
high--;
}
while (vec[low] <= pivoteKey && low < high)
{
low++;
}
if (low < high)
{
swap(vec[low], vec[high]);
}
}
vec[l] = vec[low];
vec[low] = pivoteKey;
QSort(vec, l, low - 1);
QSort(vec, low + 1, r);
}
};
void display(vector<int> vec)
{
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
cout << endl;
}
int main()
{
vector<int> vec = { 72, 6, 57, 88, 60, 42, 83, 73, 48, 85,101, 2, 7, 78, 8 };
display(vec);
cout << "***************************************************" << endl;
Solution s;
s.QSort(vec, 0, 14);
display(vec);
system("pause");
return 0;
}