Uploaded by pavan kalyan

BUBBLE SORT SWAP COUNT

advertisement
Description
Write a bubble sort program that prints the number of swaps made after M number of iterations (In this
case, ‘M’ should be an input value).
For example, if M = 0, the bubble sort program will perform 0 swaps in 0 iterations.
In bubble sort, an iteration is defined as the total number of times the outer loop runs. Assume that:
1) M <= the array size and
2) the program sorts in descending order.
The code should ask the user to input the values for M, the array size, and finally the elements of the
array. So, there will be three types of inputs —
Input 1: The value of M
Input 2: The size of the array
Input 3: The elements inside the array
import java.util.Scanner;
public class Source
{
static
{
int
int
int
int
for
{
i n t t o t a l B u b b l e S o r t S w a p s ( i n t [ ] a r r a y, i n t M )
s i z e = a r r a y. l e n g t h ;
var = 0;
totalSwaps = 0;
i, j, temp;
(i = 0; i < M; i++)
for (j = 0; j < M - i ; j++)
{
if (array[j] < array[j + 1])
{
// swap arr[j] and arr[j+1]
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
totalSwaps++;
}
}
}
return totalSwaps;
}
// Driver program
public static void main(String[] args)
{
int count;
int i;
Scanner input = new Scanner(System.in);
count = input.nextInt();
int[] array = new int[count];
for (i = 0; i < count; i++) {
array[i] = input.nextInt();
}
int M = input.nextInt();
input.close();
t o t a l B u b b l e S o r t S w a p s ( a r r a y, M ) ;
}
}
error:RUNTIME ERROR
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2 at
Source.totalBubbleSortSwaps(Source.java:17) at
Source.main(Source.java:49)
Download