Jan 18, 2002 Reading assignment: Deitel and Deitel Chapter 4.6, 4.7, 4.8 -or read the web links below for info on bubble sort Sorting arrays - Sorting is a very important problem in computer science. There are many algorithms that have been invented for sorting arrays, and they vary in their speed. If an array is large, it's very important to use a fast algorithm. - There are some algorithms that are easy to understand and easy to implement, but very poor performers and so they're never used in practice. One of these is called the bubble sort and we're going to learn it. - If an array has n entries, we will make n-1 passes through the array. On the first pass, compare successive elements (compare a[0] to a[1], then a[1] to a[2], etc.) Each time the two elements are in the wrong order, swap them (you need a variable to hold one of the values while you swap them). Proceed like this all the way to the end of the array. On the second pass, do the same thing, except that you can stop before the last compare, because the last element is already in the right place. The third pass is the same, except that you can omit the last two compares. Continue with this pattern until you have done n-1 passes, and the elements will be sorted - Know that there are better sort algorithms and two famous ones are called quick sort and heap sort - Read section 4.7 in Deitel and Deitel, which gives an example of a program that uses a bubble sort. File I/O - #include <fstream> - Declare an ofstream variable for a file you want to write to - Declare an ifstream variable for a file you want to write to - to open, for example: outfile.open("foo.txt", ios::out); infile.open("foo2.txt", ios::in); - To check if the file is open, use file.is_open(); - To write to a file, use the stream insertion character, for example outfile << num << endl; - To read from a file, use the stream extraction character, for example infile >> num; - To close a file, use file.close();
Here's the bubble sort from class (slightly better than the text's algorithm):
Here's the program from class that inputs the list from a file and outputs sorted list to file:
Here's a cool web site with an animation of bubble sort:
If you don't own Deitel and Deitel, you can read about the bubble sort on the first couple paragraphs of this web site (from the University of Hawaii):