按以下方式对整数数组的元素进行排序:第一个元素是数组的最大值,第二个元素是最小值,第三个元素是第二个最小值,第四个元素是该数组的第二个最大值数组并继续。
让我们举个例子来更好地理解这个概念,
Input : 4 1 8 2 9 3 7 Output : 9 1 8 2 7 3 4 Explanation : The elements in a sorted way is 1 2 3 4 7 8 9. Now, let’s create it in the manner we wanted it i.e. alternate sorted form. So, the largest element of the array first i.e. 9 followed by 1 which is the smallest element of the array i.e. 1 next comes 8 , 2 , 7 , 3, 4.
现在我们已经了解了这个概念,我们可以开发一个解决此问题的解决方案。因此,一种可能的解决方案是对数组进行排序并打印此排序后的数组的最后一个元素和第一个元素。让我们基于此解决方案创建一个算法。
Step 1 : Sort the array. Step 2 : Create two pointers one for traversing from start and other pointer for traversing from end. Step 3 : Print values of the pointer in alternate form and increase the value of the iterator.
#include <iostream> using namespace std; void alternateSort(int arr[], int n) ; void swap(int *xp, int *yp) ; void selectionSort(int arr[], int n) ; int main(){ int arr[] = { 4,1,8,2,9,3,7}; int n = sizeof(arr)/sizeof(arr[0]); alternateSort(arr, n); return 0; } void alternateSort(int arr[], int n){ selectionSort(arr, n); int i = 0, j = n-1; while (i < j) { cout << arr[j--] << " "; cout << arr[i++] << " "; } if (n % 2 != 0) cout << arr[i]; } void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int arr[], int n){ int i, j, min_idx; for (i = 0; i < n-1; i++){ min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; swap(&arr[min_idx], &arr[i]); } }
输出结果
9 1 8 2 7 3 4