0

I need an array listing the index number for a list of n elements and when I sort it in descending order, I need that same number to be with the element. Here's the code I have so far:

#include <iostream>
using namespace std;

int Partition(int low,int high,int arr[]);
void Selection_sort(int low,int high,int arr[]);
int main()
{
int *a,n,low,high,i,count;
cout<<"/**************************Selection Sort Algorithm Implementation*****************/";
cout<<"Enter number of elements: ";
cin>>n;

a=new int[n];

cout<<"enter the elements: "<<endl;
for(i=0;i<n;i++)
{
               cin >> a[i];
}
//for(i=0;i<n;i++)
//a[i]=rand()%100;


cout<<"Element: \tInitial Order of elements: \tIndex"<<endl;
 for(i=0;i<n;i++)
            
  cout<<i+1<<"\t"<<a[i]<<"\t"<<count<<endl;


high=n-1;
low=0;
Selection_sort(low,high,a);
cout<<"Element: \tFinal Array After Sorting: \tIndex:"<<endl;

  for(i=0;i<n;i++)
  cout<<i+1<<"\t"<<a[i]<<"\t"<<count<<endl;

system("pause");
return 0;

}


int Partition(int low,int high,int arr[])
{ int i,high_vac,low_vac,pivot/*,itr*/;
   pivot=arr[low];
   while(high>low)
{ high_vac=arr[high];

  while(pivot>high_vac)
  {
    if(high<=low) break;
    high--;
    high_vac=arr[high];
  }

  arr[low]=high_vac;
  low_vac=arr[low];
  while(pivot<low_vac)
  {
    if(high<=low) break;
    low++;
    low_vac=arr[low];
  }
  arr[high]=low_vac;
}
  arr[low]=pivot;
   return low;
}

void Selection_sort(int low,int high,int arr[])
{
  int Piv_index,i;
  if(low<high)
  {
   Piv_index=Partition(low,high,arr);
   Selection_sort(low,Piv_index-1,arr);
   Selection_sort(Piv_index+1,high,arr);
  }
}
2
Contributors
1
Reply
4
Views
9 Years
Discussion Span
Last Post by ArkM
0

Regrettably no background demons which capable to trace your Selection_sort array elements shuffling. You must change Selection_sort code to assign not only elements of
processed array but also synchronously move its initial position in "parallel array".

Add 4th array parameter to Selection_sort function (and add corresponded temp variables for pivot, low-vac and high_vac local variables) then modify all occurences of arr element assignments. Fill this array with numbers in range low..high (initial positions) then call your new Selection sort...

Another possible solution in C++ style: make a template on the base of Selection_sort code to sort not only base int arrays but (for example) elements of

struct SortedElement {
    int value;
    int initPos;
    bool operator<(const SortedElement&) const;
};

It's the other story...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.