sort排序
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
void BubbleSort(int list[], int n);
int main()
{
int list[5] = {1, 4, 2, 3};
BubbleSort(list, 5);
return 0;
}
void BubbleSort(int list[], int n)
{
for(int i = 0; i < n; i++)
{
sort(list, list + n, greater<int>()); //less<int>()
cout << list[4 - i] << endl;
}
}
选择排序:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
void SelectSort(int* list, int n);
int main()
{
int list[6] = {11, 4, 2, 13, 7};
SelectSort(list, 6);
return 0;
}
void SelectSort(int* list, int n)
{
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n - 1; j++)
{
if(list[i] < list[j])
swap(list[i], list[j]);
else continue;
}
cout << list[i] << endl;
}
}
折半查找(二分查找)
前提:数据提前排序
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int BinarySort(int* list, int n, int num);
int main()
{
int list[6] = {1, 4, 12, 13, 17};
int n = BinarySort(list, 6, 12);
cout << n;
return 0;
}
int BinarySort(int* list, int n, int num)
{
int low, mid, high;
low = 0, high = n - 1;
while(low <= high)
{
mid = (low + high)/2;
if(list[mid] == num)
return mid;
else if(list[mid] < num)
low = mid + 1;
else
high = mid - 1;
}
return 0;
}