Download code

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.
1213 Retrieved from: http://en.literateprograms.org/Merge_sort_(Java)?oldid=18559
14 */1516classMergeSortArray{17privatestaticfinalintminMergeSortListSize=60;181920publicstaticvoidmergeSortArray(int[]a, intstart, intend){21int[]temp=newint[end-start];22inti1, i2, tempi, middle;2324if((end-start)<minMergeSortListSize){25/* Use insertion sort for small datasets. */26for(inti=start;i<end;i++){27intj, v=a[i];28for(j=i-1;j>=start&&a[j]>v;j--)29a[j+1]=a[j];30a[j+1]=v;31}32return;33}34middle=start+(end-start)/2;35mergeSortArray(a, start, middle);36mergeSortArray(a, middle, end);37i1=start;38i2=middle;39tempi=0;40while(i1<middle&&i2<end)41if(a[i1]<=a[i2])42temp[tempi++]=a[i1++];43else44temp[tempi++]=a[i2++];45while(i1<middle)46temp[tempi++]=a[i1++];47while(i2<end)48temp[tempi++]=a[i2++];49System.arraycopy(temp, 0, a, start, end-start);50}5152publicstaticvoidmain(String[]argv){53intsize=Integer.parseInt(argv[0]);54int[]a=newint[size];55java.util.Randomrand=56newjava.util.Random(System.currentTimeMillis());57for(inti=0;i<size;i++){58a[i]=rand.nextInt()%size;59}60mergeSortArray(a, 0, size);61for(inti=1;i<size;i++){62if(!(a[i-1]<=a[i])){63System.out.println("ERROR");64System.exit(-1);65}66}67System.out.println("SUCCESS");68System.exit(0);69}70}