Sorting Arrays

This is the second week of this course and we are still moving in a fast pace. My prior experience with programming in Java (four years ago) helped me to keep up during the first week, but this week’s assignments were a challenge for me.

One of these assignments were to sort an array filled with randomly generated numbers. There are many different ways you can sort an array in C++, each with benefits and disadvantages. The first method I tried out was the sort function included in the C++ standard library. I used the example provided from Wikipedia as a reference.

#include <algorithm>

int main() {

int array[] = { 23, 5, -10, 0, 0, 321, 1, 2, 99, 30 };

int elements = sizeof(array) / sizeof(array[0]);

std::sort(array, array + elements);

for (int i = 0; i < elements; ++i)

std::cout << array[i] << ‘ ‘;

}

(http://en.wikipedia.org/wiki/Sort_%28C%2B%2B%29)

This method worked really well to sort the short array I wrote, but I can’t say I really understand how the sorting process work and therefore I also tried using the bubble sort method.  The bubble sort is easier to explain with a picture:

(http://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif)

A bubble sort goes through the array number by number and compare them with the adjacent number, if a number has a lower value it is moved and a new comparisons are made. This will be repeated until no more moves are possible and then the array is sorted.

This method is not the ideal if you want to sort a large aray, but it is both easy to use and to understand.

Lämna en kommentar