Download code

Jump to: navigation, search

Back to Merge_sort_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

MergeSortArray.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Merge_sort_(Java)?oldid=18559
14 */
15 
16 class MergeSortArray {
17     private static final int minMergeSortListSize  =  60;
18 
19 
20     public static void mergeSortArray(int[] a, int start, int end) {
21         int[] temp = new int[end-start];
22 	int i1, i2, tempi, middle;
23 
24         if ((end-start) < minMergeSortListSize) {
25 	    /* Use insertion sort for small datasets. */
26 	    for (int i=start; i < end; i++) {
27 	        int j, v = a[i];
28 	        for (j = i - 1; j >= start && a[j] > v; j--)
29 	            a[j + 1] = a[j];
30 	        a[j + 1] = v;
31 	    }
32 	    return;
33 	}
34         middle = start + (end-start)/2;
35         mergeSortArray(a, start, middle);
36         mergeSortArray(a, middle, end);
37         i1 = start;
38 	i2 = middle;
39 	tempi = 0;
40 	while (i1 < middle && i2 < end)
41 	    if (a[i1] <= a[i2])
42 	        temp[tempi++] = a[i1++];
43 	    else
44 	        temp[tempi++] = a[i2++];
45 	while (i1 < middle)
46 	    temp[tempi++] = a[i1++];
47 	while (i2 < end)
48 	    temp[tempi++] = a[i2++];
49         System.arraycopy(temp, 0, a, start, end-start);
50     }
51 
52     public static void main(String[] argv) {
53         int size = Integer.parseInt(argv[0]);
54         int[] a = new int[size];
55         java.util.Random rand = 
56             new java.util.Random(System.currentTimeMillis());
57         for (int i=0; i<size; i++) {
58             a[i] = rand.nextInt() % size;
59         }
60         mergeSortArray(a, 0, size);
61         for (int i=1; i<size; i++) {
62             if (!(a[i-1] <= a[i])) {
63                 System.out.println("ERROR");
64                 System.exit(-1);
65             }
66         }
67         System.out.println("SUCCESS");
68         System.exit(0);
69     }
70 }


hijacker
hijacker
hijacker
hijacker