Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sample/mergesort/MergeSortTest.java
38833 views
/*1* Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/222324/* @test25* @summary Test MergeSort26*27* @library /src/share/sample/forkjoin/mergesort28* @build MergeSortTest MergeDemo MergeSort29* @run testng MergeSortTest30*/3132import java.util.Arrays;33import java.util.Random;3435import org.testng.annotations.Test;3637public class MergeSortTest {38private Random random;39private MergeSort target;4041public MergeSortTest(Random random, MergeSort target) {42this.random = random;43this.target = target;44}4546@Test47public static void doTest() {48MergeSortTest test = new MergeSortTest(new Random(), new MergeSort(Runtime.getRuntime().availableProcessors() * 4));49test.run();50}5152private int[] generateArray(int elements) {53int[] array = new int[elements];54for (int i = 0; i < array.length; ++i) {55array[i] = random.nextInt(10);56}57return array;58}5960private void run() {61testSort();62testSortSingle();63testSortEmpty();64testLong();65}6667public void testLong() {68for (int i = 0; i < 1000; ++i) {69int elements = 1 + i * 100;7071int[] array = generateArray(elements);72int[] copy = Arrays.copyOf(array, array.length);73Arrays.sort(copy);74target.sort(array);75assertEqual(copy, array);76}77}7879private void testSortEmpty() {80int[] array = { };81target.sort(array);82assertEqual(new int[] { }, array);83}8485private void testSortSingle() {86int[] array = { 1 };87target.sort(array);88assertEqual(new int[] { 1 }, array);89}9091private void testSort() {92int[] array = { 7, 3, 9, 0, -6, 12, 54, 3, -6, 88, 1412};93target.sort(array);94assertEqual(new int[] { -6, -6, 0, 3, 3, 7, 9, 12, 54, 88, 1412 }, array);95}9697private void assertEqual(int[] expected, int[] array) {98if (!Arrays.equals(expected, array)) {99throw new RuntimeException("Invalid sorted array!");100}101}102103104}105106107