Java Reference
In-Depth Information
66
// if left array is empty
67
if (leftIndex == middle2)
68
// copy in rest of right array
69
while (rightIndex <= right)
70
combined[combinedIndex++] = data[rightIndex++];
71
else // right array is empty
72
// copy in rest of left array
73
while (leftIndex <= middle1)
74
combined[combinedIndex++] = data[leftIndex++];
75
76
// copy values back into original array
77
for ( int i = left; i <= right; i++)
78
data[i] = combined[i];
79
80
// output merged array
81
System.out.printf( " %s%n%n" ,
82
subarrayString(data, left, right));
83
} // end method merge
84
85
// method to output certain values in array
86
private static String subarrayString( int [] data, int low, int high)
87
{
88
StringBuilder temporary = new StringBuilder();
89
90
// output spaces for alignment
91
for ( int i = 0 ; i < low; i++)
92
temporary.append( " " );
93
94
// output elements left in array
95
for ( int i = low; i <= high; i++)
96
temporary.append( " " + data[i]);
97
98
return temporary.toString();
99
}
100
101 public static void main(String[] args)
102 {
103 SecureRandom generator = new SecureRandom();
104
105 int [] data = new int [ 10 ]; // create array
106
107 for ( int i = 0 ; i < data.length; i++) // populate array
108 data[i] = 10 + generator.nextInt( 90 );
109
110 System.out.printf( "Unsorted array:%n%s%n%n",
111 Arrays.toString(data)); // display array
112
113
114 System.out.printf( "Sorted array:%n%s%n%n",
115 Arrays.toString(data)); // display array
116 }
117 } // end class MergeSortTest
mergeSort(data); // sort array
Fig. 19.6 | Sorting an array with merge sort. (Part 3 of 5.)
Search WWH ::




Custom Search