我們有一個正整數型別的數組,假設為arr[],大小任意。任務是重新排列數組,使得所有奇數索引位置的元素的值大於偶數索引位置的元素,並列印結果。
輸入 − int arr[] = {2, 1, 5, 4, 3, 7, 8}
輸出 − 排列前的陣列:2 1 5 4 3 7 8 將陣列重新排列,使得每個奇數索引的元素都大於其前一個元素:1 4 2 5 3 8 7
解釋 - 我們給定一個大小為7的整數數組。現在,如果偶數索引的元素較大,我們將交換偶數索引處的元素和奇數索引處的元素
Arr[0] > arr[1] = call swap = {1, 2, 5, 4, 3, 7, 8} Arr[2] > arr[3] = call swap = {1, 2, 4, 5, 3, 7, 8} Arr[6] > arr[5] = call swap = {1, 2, 4, 5, 3, 8, 7} Arr[2] > arr[1] = call swap = {1, 4, 2, 5, 3, 8, 7}
輸入− int arr[] = {3, 2, 6, 9}
輸出− 排列前的陣列: 3 2 6 9 Rearrangement of an array such that every odd indexed element is greater than it previous is: 2 3 6 9
Explanation − we are given an integer array of size#Explanation
− we are given an integer array of size 4. Nowwe the elements at even index with the elements at odd index if even indexed elements are greater i.e. Arr[0] > arr[1] = call swap = {2, 3, 6, 9}. No need to further call the swap = {2, 3, 6, 9}. No need to further call the swap method the swap method as all the elements at positions satisfies the conditionsApproach used in the below program is as follows
#include <iostream> using namespace std; void Rearrangement(int arr[], int size){ int ptr = size - 1; for(int i = 0; i < ptr; i = i+2){ if(arr[i] > arr[i+1]){ swap(arr[i], arr[i+1]); } } if(size & 1){ for(int i = ptr; i > 0; i = i-2){ if(arr[i] > arr[i-1]){ swap(arr[i], arr[i-1]); } } } } int main(){ //input an array int arr[] = {2, 1, 5, 4, 3, 7, 8}; int size = sizeof(arr) / sizeof(arr[0]); //print the original Array cout<<"Array before Arrangement: "; for (int i = 0; i < size; i++){ cout << arr[i] << " "; } //calling the function to rearrange the array Rearrangement(arr, size); //print the array after rearranging the values cout<<"\nRearrangement of an array such that every odd indexed element is greater than it previous is: "; for(int i = 0; i < size; i++){ cout<< arr[i] << " "; } return 0; }
輸出
如果我們執行上述程式碼,將會產生以下輸出###Array before Arrangement: 2 1 5 4 3 7 8 Rearrangement of an array such that every odd indexed element is greater than it previous is: 1 4 2 5 3 8 7###
以上是重新排列一個數組,使得每個奇數索引的元素都大於其前一個元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!