Merger proof is stable

I wrote a merge algorithm. When I run the following test:

public static void main(String[] args){
    Integer[] arr = {3,7,9,11,0,-5,2,5,8,8,1};
    List<Integer> list = new ArrayList<>();
    list.addAll(Arrays.asList(arr)); // asList() returns fixed size list, so can't pass to mergesort()
    List<Integer> result = mergesort(list);
    System.out.println(result);
  }

I get [-5, 0, 1, 2, 3, 5, 7, 8, 8, 9, 11]that is correct. However, I know that mergesort is a stable view, so how can I write a test that can prove that two 8 are in the order in which they were originally?

EDIT: Since I used the class Integer, not the primitive ints, I decided that I could just get it hashCode(), since it Integerextends the base class Object.

However, when I tried

Integer[] arr = {3,7,9,11,0,-5,2,5,8,8,1};
System.out.println(arr[8].hashCode());
System.out.println(arr[9].hashCode());

I only get:

8
8
+4
source share
3 answers

, , - Integer. :

Integer eight = new Integer(8);
Integer anotherEight = new Integer(8);

a == b; //Returns false
a.equals(b); //Returns true

, , .

EDIT: , Integer.hashcode() , hascode

int, Integer.

+5

, Key-Value, , this

( ):

public class Tuple<X, Y> { 
  public final X x; 
  public final Y y; 
  public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
  } 
} 

:

  public static void main(String[] args)
  {
    Integer[] arr = {new Tuple(3,0),new Tuple(7,1),new Tuple(9,2) ,new Tuple(11,3), new Tuple(0,4), new Tuple(-5,5), new Tuple(2,6), new Tuple(5,7), new Tuple(8,8), new Tuple(8,9), new Tuple(1,10)};
    List<Tuple<Integer,Integer>> list = new ArrayList<>();
    list.addAll(Arrays.asList(arr)); // asList() returns fixed size list, so can't pass to mergesort()
    List<Integer> result = mergesort(list);
    System.out.println(result);
  }

, , , (8,8), (8,9)

0

, , . . n n 1, , . k-way, k , , .

, 2 , , , , .

0
source

Source: https://habr.com/ru/post/1681236/


All Articles