Saturday, November 8, 2014

Bubble sort

5.10 Lab  Write a method that sorts an array of integers using bubble sort. The method can use an
auxiliary method that swaps two entries in the array. Use a nested for loop to implement
the bubble sort. The method should modify the input array and have void return type.
Test your method with different inputs.


public class Arithmetic {
static int[] array = {10,7,6,3,2,1};
public static void main(String[] args) {
print();
bubbleSort();
}

public static void bubbleSort(){
for (int n = 0; n<array.length-1; n++)
{
for (int i = 0; i<array.length-1; i++)
{
if (array[i]>array[i+1])
{
swap(i);
}
}
}
}

public static void swap(int x){
int temp = array[x];
array[x] = array[x+1];
array[x+1] = temp;
print();
}

public static void print(){
String output = "";
for (int i = 0; i<array.length; i++)
{
output = output + array[i] +" ";
}
System.out.println(output);
}
}



No comments:

Post a Comment