Wednesday, September 1, 2010

Sort Arrays

A really important function when handling data is to sort it.
The .Net framework provides a lot of methods to do that, arrays for example can be sorted easily via Array.Sort().
This sorts the given array in increasing order using the Quicksort algorithm, which is one of the best sorting algorithms.
The following example sorts an integer array in increasing order (when using strings or characters these are sorted alphabetically):

int[] TestArray = new int[] { 5, 3, 4, 1, 2 }; // short way to initialize arrays

The result is finally directly saved in TestArray, meaning the data manipulation has been done in the array itself, as in .Net arrays are reference types.
To order the array in decreasing order, after sorting it the function Array.Reverse() can be called to reverse the array:

For readers interested in the theory and also for publicity in my own cause, here you find an Android app by me which visualizes different sorting algorithms (amongst others Quicksort).

No comments:

Post a Comment