Home > database >  Did I correctly translate this pseudocode into Java? I'm particularly looking at line 3 in the
Did I correctly translate this pseudocode into Java? I'm particularly looking at line 3 in the

Time:01-24

Did I correctly translate this pseudocode into Java? I am particularly looking at line 3 in the pseudocode for this sorting algorithm.

Here is the pseudocode that I am attempting to translate:

    Sort-Array(A)
    for i = 1 to (A.length – 1)
        for j = (i   1) to A.length
            if (A[j] > A[i])
                // swap A[i] and A[j]
                buffer = A[j]
                A[j] = A[i]
                A[i] = buffer

My translation:

static void bubbleSort(int array[]) {
  int size = array.length;
  
  // loop to access each array element
  for (int i = 1; i < size - 1; i  )
   
     // loop comparing the array elements
     for (int j = i   1; j < size; j  )
     
        // compare two adjacent elements
        // changing > to < to sort in either order
        if (array[j] > array[i]) {
        
           // swapping elements. 
           int buffer = array[j];
           array[j] = array[i];
           array[i] = buffer;
           
        }

CodePudding user response:

Yes, but there is one mistake. In the pseudocode you start with i = 1, because in pseudocode we dont start counting at 0. in your programm you have to start at 0, because the first element of an array start at array[0], not array[1].

CodePudding user response:

Line #3 translated correctly but that's not actually a bubble sort algorithm. Here if (array[j] > array[i]) you compare all the further elements with i element and in bubble sort you need to compare only neighbor elements of array. So, basically to transform it to bubble sort you need to compare j with j-1

  •  Tags:  
  • Related