Algorithms The Bubble Sort The Bubble Sort example essay topic

424 words
Introduction One of the fundamental problems of computer science is ordering a list of items. There's a plethora of solutions to this problem, known as sorting algorithms. Some sorting algorithms are simple and intuitive, such as the Bubble sort. Others, such as the Quick sort can be extremely complicated, but produce lightening-fast results. The common sorting algorithms can be divided into two classes by the complexity of their algorithms. The two classes of sorting algorithms are O (n 2), which includes the Bubble, Insertion and Selection sorts; and O (n log n) which includes the Heap, Merge and Quick sorts.

In addition to algorithmic complexity, the speed of the various sorts can be compared with empirical data. Since the speed of a sort can vary greatly depending on what data set it sorts, accurate empirical results require several runs of the sort be made and the results averaged together. The empirical data used in this project is the average of several runs against random data sets. The Algorithms The Bubble Sort The bubble sort works by comparing each item in the list with the item next to it, and swapping them if required. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items (in other words, all items are in the correct order). This causes larger values to "bubble" to the end of the list while smaller values "sink" towards the beginning of the list.

The bubble sort is generally considered to be the most inefficient sorting algorithm in common usage. Under best-case conditions (the list is already sorted), the bubble sort can approach a constant O (n) level of complexity. General-case is an abysmal O (n 2). Pros: Simplicity and ease of implementation.

Cons: Horribly inefficient. void Bubble Sort (int array, int size) { int i, j, temp; bool swapped; for (i = size-1; i = 0; i -- ) { swapped = false; for (j = 0; j low) { mid = (low + high) / 2; MSort (array, temp, low, mid); MSort (array, temp, mid+1, high); Merge (array, temp, low, mid+1, high); } } void Merge Sort (int array, int temp, int size) { MSort (array, temp, 0, size-1); } void Merge (int array, int temp, int low, int mid, int high) { int lowend, size, index; lowend = mid - 1; index = low; size = high - low + 1; while ( (low.