C ++程序用于对除子数组中的元素之外的数组进行排序
给定一个数组 A 正整数,按升序对数组进行排序,使得未排序数组中给定子数组(开始和结束索引是输入)中的元素保持不动,所有其他元素都被排序。
例子 :
Input : arr[] = {10, 4, 11, 7, 6, 20}
l = 1, u = 3
Output : arr[] = {6, 4, 11, 7, 10, 20}
We sort elements except arr[1..3] which
is {11, 7, 6}.
Input : arr[] = {5, 4, 3, 12, 14, 9};
l = 1, u = 2;
Output : arr[] = {5, 4, 3, 9, 12, 14 }
We sort elements except arr[1..2] which
is {4, 3}.
方法:将除给定数组的给定限制之外的所有元素复制到另一个数组。然后使用排序算法对另一个数组进行排序。最后再次将排序后的数组复制到原始数组。复制时,跳过给定的子数组。
C++
// CPP program to sort all elements except
// given subarray.
#include
using namespace std;
// Sort whole array a[] except elements in
// range a[l..r]
void sortExceptUandL(int a[], int l, int u, int n)
{
// Copy all those element that need
// to be sorted to an auxiliary
// array b[]
int b[n - (u - l + 1)];
for (int i = 0; i < l; i++)
b[i] = a[i];
for (int i = u+1; i < n; i++)
b[l + (i - (u+1))] = a[i];
// sort the array b
sort(b, b + n - (u - l + 1));
// Copy sorted elements back to a[]
for (int i = 0; i < l; i++)
a[i] = b[i];
for (int i = u+1; i < n; i++)
a[i] = b[l + (i - (u+1))];
}
// Driver code
int main()
{
int a[] = { 5, 4, 3, 12, 14, 9 };
int n = sizeof(a) / sizeof(a[0]);
int l = 2, u = 4;
sortExceptUandL(a, l, u, n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}
输出 :
4 5 3 12 14 9
有关详细信息,请参阅有关排序数组的完整文章,子数组中的元素除外!