Alternate sorting

Alternate sorting:

We maintain two pointers, one from beginning and one from end in sorted array. We alternatively print elements pointed by two pointers and move them toward each other.

program:

#include<stdio.h>
void sort(int a[],int n)
{
    int i,j;
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(a[i]<a[j])
            {
                int temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    for(i=0,j=n-1;i<=j;i++,j--)
    {
        if(i==j)
        {
            printf("%d",a[i]);
        }
        else
        {
            printf("%d %d ",a[i],a[j]);
        }
    }
}
int main()
{
    int arr[]={9,7,2,3,6,5,10};
    //sort
    int n = sizeof(arr)/sizeof(arr[0]);
    sort(arr,n);


output:

10 2 9 3 7 5 6                                                                                                                                 
                   

Comments

Popular posts from this blog

C program to print the following Pattern

For any given matrix find the path from the start to the end which gives the maximum sum. Traverse only right or down. Example: starting index is 15 (left top) and ending index is 10 (bottom right) 15 25 30 45 25 60 70 75 10 O/P:15->45->70->75->10 sum is 215

c++ program to print string along the diagonals of the matrix.