Google

Sorting – General Selection Sort

Written on:December 8, 2012
Comments are closed

Sorting – General Selection Sort

Steps: 

  1. Fetch the numbers to be sorted in an array.
  2. Push these numbers one by one to a priority queue.  (Any priority-lower or higher may be considered).

Case 1:  Lower values with high priority for ascending order.

Case 2:  Higher values with high priority for descending order.

3. Pop all the elements from the priority queue to the array one by one.

4. Display the array, which is now in sorted order.

Example:  Let us consider that lower values are given high priority.

Program to implement General Selection Sort:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#define MAX 5

struct queue
{
int arr[MAX];
int front,rear;
};

void push(struct queue *q,int x)
{int f,r,j;
if(q->front==-1)
{
q->arr[0]=x;
q->front=q->rear=0;
return;
}
f=q->front;
r=q->rear;
if(q->rear==MAX-1)
{
printf(“\nQueue full! Overflow.”);
exit(1);
}
while(f<=r && q->arr[f]<x)
{f++;
}
for(j=r;j>=f;j–)
q->arr[j+1]=q->arr[j];
q->arr[f]=x;
q->rear++;
}

int pop(struct queue *q)
{
if(q->front==-1)
{printf(“\nQueue empty! Underflow.”);
exit(1);
}
return(q->arr[(q->front)++]);
}

void display(struct queue *q)
{
int f,r;
if(q->front == -1)
{
printf(“\nQueue empty…!”);
exit(1);
}
f=q->front;
r=q->rear;
while(f!=r)
printf(“%d\t”,q->arr[f++]);
printf(“%d\t”,q->arr[f]);
}

void main()
{
int arr[MAX], i;
struct queue q;
q.front=q.rear=-1;
clrscr();
for(i=0;i<MAX;i++)
{
printf(“\nEnter array elements?”);
scanf(“%d”,&arr[i]);
}
for(i=0;i<MAX;i++)
{push(&q,arr[i]);
}
printf(“\n\nDisplaying queue elements…!\n\t”);
display(&q);
printf(“\n\nSorted Array is:”);
for(i=0;i<MAX;i++)
{
arr[i]=pop(&q);
printf(“%d\t”,arr[i]);
}
getch();
}

 

Sorry, the comment form is closed at this time.