Can I see another sample of this program? I'm having difficulty in understanding it [closed]

StackOverflow https://stackoverflow.com/questions/22161146

  •  19-10-2022
  •  | 
  •  

Question

int j = 0;              
while (j < A.length) {          
    i = j + 1;               
    while (i < A.length) {      
        if(A[i] < A[j])         
            //swap              
            int temp = A[i];        
            A[i] = A[j];
            A[j] = temp;            
        }                   
        i++;                
    }                   
    j++;        

}

a program that will output the number of swaps that will be executed for different array lengths as enumerated below: a. 100 b. 1,000 c. 10,000 d. 100,000 e. 1,000,000

Was it helpful?

Solution

initiate counter (j)
 while j is less than length(A) -
   /* if this pair is out of order */
   if A[index-1] > A[index] then
     /* swap them and remember something changed */
     swap( A[index-1], A[index] )
     swapped = true
   end if
 end while
increment counter (j)

p.s your brackets are not matching are you missing a code segment?

OTHER TIPS

If I understand what you're asking then it is important to note that line indentation is not semantically meaningful in Java (you need braces),

if(A[i] < A[j]) { // <-- Open brace         
  //swap              
  int temp = A[i];        
  A[i] = A[j];
  A[j] = temp;   
} // <-- Close brace
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top