Hi,

I have made some sorting function based on finding largest element and swapping its place with last element of array and then searching largest element of rest of array and putting it on one place before last one and so on.

I am curious about is there a name for sorting of this type?
I searched Wikipedia, and the most similar sorting method seems to be a Heap sort.

Here is the sorting function I made:

int Biggest(int Niz[], int n){
    int x= Niz[0];
        for(int i=1;i<n;++i)
        if(Niz[i]>x) x=Niz[i];
    return x;
}

void Sort(int *Niz, int n){
     int *temp=new int;
         for(;n>1;--n){
             *temp=Biggest(Niz,n);
             for(int i=0;i<n;++i){
                 if((*temp)==Niz[i]){
                 Niz[i]=Niz[n-1];
                 Niz[n-1]=(*temp);                    
                 }
             }              
        }
     delete temp;
}

Does it suit with Heap Sort?

Thanks!

Recommended Answers

All 2 Replies

Your algorithm is called "Selection Sort".

And no, it is not similar to heap sort. It is true that heap sort has a second phase where the max (or min) elements are extracted from the unsorted section and stacked at the beginning or end of the overall array. However, the main aspect of this phase is that the heap structure is always conserved. A heap structure is a way of arranging the elements of the array such that the max (or min) always appears in the first position in the array. If you set up the structure properly, you can efficiently remove the max (or min) element and update the heap structure to put the new max (or min) element at the first position. So, the heap sort algorithm first rearranges the elements of the array in a heap structure, and then it takes the max (or min), puts it at the last position in the array (before the start of the sorted section of the array), then it updates the heap structured section of the array, and repeats until the entire array is sorted. So, the second phase is similar to Selection Sort, but the important thing is that you don't have to look for the maximum element (which is linear-time) but instead maintain the heap structure (which is log-time, which is much faster).

You can explore heap sort by using the standard sort_heap algorithm, see the example on the reference page.

Thanks, I'm glad you answered!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.