You are on page 1of 2

import java.util.

*;
public class Sorting
{
// Helper methods
static int [] createArray()
{
// Create array with 10 random values
int [] list = new int[10];
Random r = new Random();
for (int i = 0; i < list.length; i++)
{
list[i] =r.nextInt(99) + 1; // 1-99
}
return list;
}
static void printArray (int [] list)
{
System.out.print("[");
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
}
System.out.println("]");
}
static void bubblesort (int [] list)
{ // Naive bubblesort
for (int pass = 0; pass < list.length - 1; pass++)
{
for (int i = 0; i < list.length - 1; i++)
{
// COmpare adjacent elements
if (list[i] > list[i+1])
{
// Swap out-of-order elements
int temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
} // end of if
} // end of inner loop
printArray(list); // show current progress
} // end of outer loop
} // end of method
public static void main (String [] args)
{
int [] foo = {1, 2, 3, 5, 4, 6, 7, 8, 9, 10};//createArray();
printArray(foo); // print initial state
optBubblesort(foo); // sort the array
printArray(foo); // print sorted result
}
static void optBubblesort (int [] list)
{ // Optimized bubblesort
int swaps = 1; // prime the loop

for (int pass = 0;


{
swaps = 0;
for (int i
{
//
if
{

swaps > 0 && pass < list.length - 1; pass++)


// reset our count
= 0; i < list.length - 1; i++)
COmpare adjacent elements
(list[i] > list[i+1])

// Swap out-of-order elements


int temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
swaps++; // we made at least one swap
} // end of if
} // end of inner loop
printArray(list); // show current progress
} // end of outer loop
} // end of method
}

You might also like