Parity Sorting Algorithm

Source: Internet
Author: User

奇偶排序,或奇偶换位排序,或砖排序,是一种相对简单的排序算法,最初发明用于有本地互连的并行计算。这是与冒泡排序特点类似的一种比较排序。该算法中,通过比较数组中相邻的(奇-偶)位置数字对,如果该奇偶对是错误的顺序(第一个大于第二个),则交换。下一步重复该操作,但针对所有的(偶-奇)位置数字对。如此交替进行下去。

使用奇偶排序法对一列随机数字进行排序的过程

本文地址:http://www.cnblogs.com/archimedes/p/odd-even-sort-algorithm.html,转载请注明源地址。

处理器数组的排序

在并行计算排序中,每个处理器对应处理一个值,并仅有与左右邻居的本地互连。所有处理器可同时与邻居进行比较、交换操作,交替以奇-偶、偶-奇的顺序。该算法由Habermann在1972年最初发表并展现了在并行处理上的效率。

该算法可以有效地延伸到每个处理器拥有多个值的情况。在Baudet–Stevenson奇偶合并分区算法中,每个处理器在每一步对自己所拥有的子数组进行排序,然后与邻居执行合并分区或换位合并。

Batcher奇偶归并排序

Batcher奇偶归并排序是一种相关但更有效率的排序算法,采用比较-交换和完美-洗牌操作。

Batcher的方法在拥有广泛互连的并行计算处理器上效率不错。

算法

举例:待排数组[6 2 4 1 5 9]

第一次比较奇数列,奇数列与它的邻居偶数列比较,如6和2比,4和1比,5和9比

[6 2 4 1 5 9]

交换后变成

[2 6 1 4 5 9]

 

第二次比较偶数列,即6和1比,5和5比

[2 6 1 4 5 9]

交换后变成

[2 1 6 4 5 9]

 

第三趟又是奇数列,选择的是2,6,5分别与它们的邻居列比较

[2 1 6 4 5 9]

交换后

[1 2 4 6 5 9]

 

第四趟偶数列

[1 2 4 6 5 9]

一次交换

[1 2 4 5 6 9]

以下表现其单处理器算法,类似冒泡排序,较为简单但效率并不特别高。

// Completed on 2014.10.8 12:05// Language: C99//// 版权所有(C)codingwu   (mail: [email protected]) // 博客地址:http://www.cnblogs.com/archimedes/#include<stdio.h>#include<stdlib.h>#include<stdbool.h>  void swap(int *a, int *b){    int t;    t = *a;    *a = *b;    *b = t;}void printArray(int a[], int count){    int i;    for(i = 0; i < count; i++)        printf("%d ",a[i]);    printf("\n");}void Odd_even_sort(int a[], int size)  {    bool sorted = false;    while(!sorted)    {        sorted = true;        for(int i = 1; i < size - 1; i += 2)        {            if(a[i] > a[i + 1])            {                swap(&a[i], &a[i + 1]);                sorted = false;            }        }        for(int i = 0; i < size - 1; i += 2)        {            if(a[i] > a[i + 1])            {                swap(&a[i], &a[i+1]);                sorted = false;            }        }    }}int main(void)   {    int a[] = {3, 5, 1, 6, 9, 7, 8, 0, 11};    int n = sizeof(a) / sizeof(*a);    Odd_even_sort(a, n);    printArray(a, n);    return 0;}

 

奇偶排序算法

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.