📜  奇偶排序/砖排序的C / C ++程序

📅  最后修改于: 2021-05-31 23:09:51             🧑  作者: Mango

这基本上是气泡排序的一种变体。该算法分为两个阶段-奇数阶段和偶数阶段。该算法一直运行到对数组元素进行排序,并在每次迭代中出现两个阶段-奇数阶段和偶数阶段。

在奇数阶段,我们对奇数索引元素执行冒泡排序,在偶数阶段,我们对偶数索引元素执行冒泡排序。

// A C++ Program to implement Odd-Even / Brick Sort
#include 
using namespace std;
  
// A function to sort the algorithm using Odd Even sort
void oddEvenSort(int arr[], int n)
{
    bool isSorted = false; // Initially array is unsorted
  
    while (!isSorted) {
        isSorted = true;
  
        // Perform Bubble sort on odd indexed element
        for (int i = 1; i <= n - 2; i = i + 2) {
            if (arr[i] > arr[i + 1]) {
                swap(arr[i], arr[i + 1]);
                isSorted = false;
            }
        }
  
        // Perform Bubble sort on even indexed element
        for (int i = 0; i <= n - 2; i = i + 2) {
            if (arr[i] > arr[i + 1]) {
                swap(arr[i], arr[i + 1]);
                isSorted = false;
            }
        }
    }
  
    return;
}
  
// A utility function ot print an array of size n
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << "\n";
}
  
// Driver program to test above functions.
int main()
{
    int arr[] = { 34, 2, 10, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    oddEvenSort(arr, n);
    printArray(arr, n);
  
    return (0);
}
输出:
-9 2 10 34

请参阅关于奇偶排序/砖块排序的完整文章,以了解更多详细信息!

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。