![]() |
|
|
Understanding Data Sorting Methods
Sorting is very important when it comes to dealing with arrays. What this process does is it sorts the elements of an array. This can save the programmer a lot of time when it comes to managing an array that may make up a large portion of a program. Before I start with the sorting methods, it is important that you understand the swap() function that will be used in all of the sorting algorithms discussed here. What this function does is that it swaps two elements in an array. A temporary variable is used in the process to make sure that the value of the first variable isn't lost. The variables first and second store the values of the two elements that are to be swapped. These are passed on to the function via a call which looks like this: swap(element1, element2)
void swap(int first, int second) There are six main sorting methods that are used in C++, however, this section will only discuss two of them: the Bubble Sort and the Selection Sort. The Bubble Sort The Bubble Sort is the simplest of the sorting methods. What it does is that it sorts the data in an array by moving the largest elements to the top. Therefore, in a sense, these elements "float up" or "bubble up" to the top. Thus, this process sorts an array of integers from highest to lowest. A while loop is used for the Bubble Sort. A variable is then used to determine the state of the array. When two consecutive elements in an array are compared, if the second is less than the first then this state variable is set to 'y' or any other character and a swap is made. The loop will end whenever the state variable is not equal to 'y'. The Selection Sort The Selection Sort is similar to the Bubble Sort. However, this sorting methods swaps two elements instead of bubbling them up to the top. Generally, this makes the Selection Sort faster than the Bubble Sort. Again, a while loop is used for the Selection Sort. This time, however, a variable (let's call it top) is set to the topmost element in the array. A second while loop is then set up within the first to compare top with every other element in the array. The highest of the elements is then found and swapped with top. This goes on until top reaches the bottom.
If you would like more detailed information on sorting methods and functions, you can find complete source codes which implement these two sorting methods as well as functions in the newly released application: C++ Coder. Check it out.
|