 |
|

|
 |

10/08/09 - Sorting an Array
|
 |
 |
 |
  | We already know how to find the minimum value in an integer array. We can sort an integer array by repeatedly finding the minimum value in the array and moving it towards the front of the array. The first time through the array, we move the very smallest value to the first position in the array. The next time through the array, we start at the second value (so the array we have to search for the minimum is one value shorter), and when we find the next smallest integer, we put that in the second position in the array. We continue this process until we've put all the values in ascending (from smallest to largest) order.
|
 |
 |
 |
 |
  | The code below carries out this method of sorting an array (called a "selection" sort), and it breaks the different operations into different methods for clarity and simplicity.
|
 |
 |
 |
 |
  | /** * Sort the values in an array from smallest to largest (ascending order) * * @author Chuck Iverson * @version 10/8/09 */ public class SortArray { public static void main(String [] args) { int [] a = {5, -3, 7, 2, 6}; // original array print(a); // print the original array sort(a); print(a); // print the sorted array } public static void sort(int [] a) { int minIndex; for (int j = 0; j < a.length; ++j) { // go thru the array a.length times minIndex = j; // assume the jth value is the min for (int i = 1+j; i < a.length; ++i) { // find the index of the real min value if (a[i] < a[minIndex]) { minIndex = i; } } swap(a,j,minIndex); // swap the real min value with the jth value } } public static void swap(int [] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void print(int [] a) { for (int i = 0; i < a.length; ++i) { System.out.print(a[i] + " "); } System.out.println(); } }
/* sample run
5 -3 7 2 6 -3 2 5 6 7
*/
|
 |
 |
 |
 |
  | Create a text file with 10 random integers in it: "ten_random_ints.txt". Write a program that reads the values from the file into an array, prints the values in the array, sorts the values in the array and prints the sorted array.
|
 |
 |
 |
 |
  | Create a text file with 10 random doubles in it: "ten_random_doubles.txt". Write a program that reads the values from the file into an array, prints the values in the array, sorts the values in the array and prints the sorted array.
|
 |
 |
 |
 |
  | Create a text file with 10 random names in it: "ten_random_names.txt". Write a program that reads the values from the file into an array, prints the values in the array, sorts the values in the array and prints the sorted array.
|
 |
 |
|


 |
 |
 |