RSS

INSERTION SORT: DESCENDING ORDER (BETTER LOGIC)

29 Mar
// THIS PROGRAM SORTS AN ARRAY IN DESCENDING ORDER USING INSERTION SORT

#include <iostream>

using namespace std;

void insertionsort(int arr[], int size);

int main()
{
 int arr[100], size;
 cout<<"Enter the size of the array \n";
 cin>>size;

 cout<<"\nInput the array \n";

 for(int i = 1;i<=size; i++)
 {
  cin>>arr[i];
 }

 arr[0] = 32767;

 insertionsort(arr,size);

 cout<<"\nThe sorted array is \n";

 for(int i = 1; i<=size; i++)
 {
  cout<<arr[i]<<' ';
 }

return 0;
}

void insertionsort(int arr[], int size)
{
 for(int j = 2; j<=size; j++)
 {
  int key = arr[j];
  int k = j-1;

  while(key>arr[k])
  {
   arr[k+1] = arr[k];
   k--;
  }

  arr[k+1] = key;
 }
}
Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: