0

I use selection sort, but I want a better sorting solution than this:

    static void SelectionSort(int[] a)
    {
        int temp, pmin;
        for (int i=0; i<a.Length-1; i++)
        {
            pmin=i;
            for (int j=i+1; j<a.Length; j++)
            if (a[j]<a[pmin])
                pmin=j;
            temp = a[i];
            a[i] = a[pmin];
            a[pmin] = temp;
        }
    }
digEmAll
  • 56,430
  • 9
  • 115
  • 140
liran63
  • 1,300
  • 2
  • 15
  • 17

6 Answers6

3

Just use:

Array.Sort(a);

Which will do a QuickSort.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

If you look on wikipedia, there is a good comparison of different sorting algorithms as far as their space and time complexity. Many are n lg n or n average time which should suit your needs nicely.

In addition, .NET comes with several sorting algorithms built in. Including Array.Sort() and List.Sort()

jb.
  • 9,921
  • 12
  • 54
  • 90
2

use Array.Sort(a) or orderby in linq

Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
1

There is no absolute winner in sorting algorithms. The efficensy depends on size, content, state of the array. You only know what is best for you.

Look here for examples and measurement.

Tigran
  • 61,654
  • 8
  • 86
  • 123
1

just use the built in function in Array: Array.Sort(a)

John Woo
  • 258,903
  • 69
  • 498
  • 492
0

To have the fastest sorting algorithm you should use heap sort .It has the lowest time complexity compared to all other sorting algorithm

A program to implement Heap Sort

#include<stdio.h>

void restoreHup(int*,int);
void restoreHdown(int*,int,int);

void main()
{
    int a[20],n,i,j,k;
    printf("   Enter the number of elements to sort : ");
    scanf("%d",&n);

    printf("Enter the elements : ");
    for(i=1;i<=n;i++){
            scanf("%d",&a[i]);
            restoreHup(a,i);
    }


    j=n;
    for(i=1;i<=j;i++)
    {
            int temp;
            temp=a[1];
            a[1]=a[n];
            a[n]=temp;
            n--;
            restoreHdown(a,1,n);
    }

    n=j;

    printf("Here is it...");
    for(i=1;i<=n;i++)
            printf("%4d",a[i]);
    }



    void restoreHup(int *a,int i)
    {
     int v=a[i];

     while((i>1)&&(a[i/2]<v))
     {
            a[i]=a[i/2];
            i=i/2;
     }
     a[i]=v;
    }

    void restoreHdown(int *a,int i,int n)
   {
    int v=a[i];
    int j=i*2;
    while(j<=n)
    {
            if((j<n)&&(a[j]<a[j+1]))
                    j++;
            if(a[j]<a[j/2]) break;

            a[j/2]=a[j];
            j=j*2;
    }
    a[j/2]=v;
   }
yatish mehta
  • 905
  • 1
  • 10
  • 25