0

*Update: Resolved did a deep copy, thanks for the help

I am using a vector of integers to simulate some sorting algorithms, when i insert numbers to the test vector and shuffle the order and pass it to a sorting function, if i pass the void sorting functions the same vector, when the vector gets sorted in a function previously passed the newly sorted vector gets passed to the function following it because it is already sorted i cannot show the sorting process. For example in my following code

@SuppressWarnings("unchecked") // Removes error given at when adding elems to int_vec
    public static void CreateVec (int array_len)
    {
      Vector <Integer> int_vec = new Vector(array_len);
      int temp_int = 1;
      int low_bound = 0;
      int high_bound = array_len - 1;

          for(int i = 0; i<array_len; i++)
          {
              int_vec.addElement(temp_int);// creating a vec in respect to array len
              temp_int ++;
          }

             Collections.shuffle(int_vec);
             System.out.println("OG vec: " + int_vec); //original vector (random order)
             BubbleSort(int_vec,array_len); //sending int_vec to bubble sort
             InsertionSort(int_vec,array_len); // retrieves newly sorted vector sorted from BubbleSort (problem)

    }

So my question follows, how can i keep sending my test vector (int_vec) with the randomly ordered elements rather than it keep sending the sorted vector to the other algorithms. Note i correctly implemented these algorithms, it works if i comment out the function calls to the other algorithm functions.

4

2 に答える 2

2

int_vecwithのコピーを作成しnew Vector<Integer>(int_vec)、そのコピーをソート メソッドに渡します。このようにして、コピーのみがソートされ、int_vecランダムに並べ替えられ、次のソート方法で再度コピーする準備が整います。

はい、これは浅いコピーですが、ここでは深いコピーは必要ありません。

于 2013-03-26T23:54:53.947 に答える
0

それは動作していないようです私は次のことをしました

Vector <Integer> int_vec = new Vector(array_len);    
Vector <Integer> copy_bub = new Vector <Integer> (int_vec);
//...//
BubbleSort(int_vec,array_len);
InsertionSort(copy_bub,array_len);

これが出力です

Output:   
    OG vec: [4, 8, 9, 6, 10, 2, 1, 5, 3, 7]
    Copy vec: [4, 8, 9, 6, 10, 2, 1, 5, 3, 7]
    Bubble Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Insertion Vec: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
于 2013-03-27T03:02:42.650 に答える