#include <iostream>
#define max_length 20
using namespace std;
int length;
int a[max_length] = {2, 3, 7, 5, 4, 6};
int result[4];
void incre_sort(int a[])
{
int p = -1, q = -1; //左右扫描
int max = a[0], min = a[length - 1];
for (int i = 0; i < length; i++)
{
//左端拐点其实没必要找到,只要找到最高点,在最高点右边的都要纳入排序范围
// if (i < length - 1 && a[i] > a[i + 1] && p == -1) //出现第一个拐点用p记录下来
// {
// p = i;
// }
if (a[i] > max)
max = a[i];
if (a[i] < max)
q = i;
}
//拓展左端点,从最右端开始,比最小点大的都要纳入排序范围,因为最小点一定要排到最左边 2,3,7,4,1,5,6
for (int i = length - 1; i >= 0; i--)
{
if (a[i] < min)
min = a[i];
if (a[i] > min)
p = i;
}
result[0] = p;
result[1] = q;
}
void decre_sort(int a[]) //对incre_sort略微改动即可
{
int p = -1, q = -1; //左右扫描
int max = a[length - 1], min = a[0];
for (int i = 0; i < length; i++)
{
if (a[i] < min)
min = a[i];
if (a[i] > min)
q = i;
}
for (int i = length - 1; i >= 0; i--)
{
if (a[i] > max)
max = a[i];
if (a[i] < max)
p = i;
}
result[2] = p;
result[3] = q;
}
int main()
{
length = 6;
// cin>>length;
incre_sort(a);
decre_sort(a);
if (result[1] - result[0] < result[3] - result[2])//升序降序比较,得到最短需要排序的子数组
cout << result[0] << ' ' << result[1] << endl;
else
{
cout << result[2] << ' ' << result[3] << endl;
}
return 0;
}
课外题:需要排序的子数组
最新推荐文章于 2022-04-02 10:01:24 发布