Chapter 7 (Web site design) Arrays 259 59 hold = c[
Chapter 7 Arrays 259 59 hold = c[ first ]; 60 c[ first ] = c[ first + 1 ]; 61 c[ first + 1 ] = hold; 62 } 63 } Fig. 7.10 Sorting an array with bubble sort. (Part 3 of 3.) Method BubbleSort receives the array as parameter b. The nested for loop on lines 46 51 performs the sort. The outer loop controls the number of passes of the array. The inner loop controls the comparisons and necessary swapping of the elements during each pass. Method BubbleSort first compares b[0]to b[1], then b[1]to b[2], then b[2] to b[3] and so on, until it completes the pass by comparing b[8] to b[9]. Although there are 10 elements, the comparison loop performs only nine comparisons. As a result of the way the successive comparisons are made, a large value may move down the array (sink) many positions (and sometimes all the way to the bottom of the array) on a single pass. However, a small value may move up (bubble) only one position. On the first pass, the largest value is guaranteed to sink to the bottom element of the array, b[9]. On the second pass, the second largest value is guaranteed to sink to b[8]. On the ninth pass, the ninth largest value sinks to b[1]. This leaves the smallest value in b[0], so only nine passes are needed to sort a 10-element array. If a comparison reveals that the two elements appear in descending order, BubbleSort calls Swap to exchange the two elements so they will be in ascending order in the array. Method Swap receives a reference to the array (which it calls c) and one integer representing the subscript of the first element of the array to be exchanged. Three assignments on lines 59 61 perform the exchange, where the extra variable hold temporarily stores one of the two values being swapped. The swap cannot be performed with only the two assignments c[ first ] = c[ first + 1 ]; c[ first + 1 ] = c[ first ]; If c[first]is 7 and c[first+1]is 5, after the first assignment, both elements of the array contain 5 and the value 7 is lost hence, the need for the extra variable hold. The advantage of the bubble sort is that it is easy to program. However, the bubble sort runs slowly, which becomes apparent when sorting large arrays. More advanced courses (often titled Data Structures or Algorithms or Computational Complexity ) investigate sorting and searching in greater depth. Note that the .NET framework includes a built- in array-sorting capability that implements a high-speed sort. To sort the array a in Fig. 7.10, you can use the statement Array.Sort( a );
We recommend high quality webhost to host and run your jsp application: christian web host services.