Skip to content

Instantly share code, notes, and snippets.

@ericrswanny
Created September 10, 2011 20:24
Show Gist options
  • Save ericrswanny/1208732 to your computer and use it in GitHub Desktop.
Save ericrswanny/1208732 to your computer and use it in GitHub Desktop.
BubbleSort algorithm implemented in java
/*============================================================================
Name : BubbleSort.java
Author : Eric Swanson
Date : Sep 10, 2011
Version :
Description :
RequiredFile: LinkedList.java
Copyright (C) 2011 Eric Swanson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
============================================================================*/
import java.util.*;
import java.io.*;
class BubbleSort
{
public static void main(String [] args) throws IOException
{
//Build a random LinkedList of integers
LinkedList ll = new LinkedList(1);
ArrayList<Integer> al = ArrayFromFile.getArrayFromFile("100");
for(int i=0; i<al.size(); i++)
{
ll.addAtHead(al.get(i));
}
//Start the time, sort the LinkedList and stop the time
long time = System.currentTimeMillis();
bubbleSort(ll);
time = System.currentTimeMillis() - time;
//print the list
ll.printList();
//print time
System.out.println("Program took: " + time + " milliseconds");
}
public static void bubbleSort(LinkedList list)
{
boolean unsorted = true;
while(unsorted)
{
int topLimit = list.getSize();
for(int i = 0; i < topLimit; i++)
{
int oneData = (Integer) list.find(i).getData();
int twoData = (Integer) list.find(i+1).getData();
System.out.println("Comparing " + oneData + " " + twoData);
//If node one is greater than node two, switch them
if(oneData > twoData)
{
list.switchWithNext(i);
}
list.printList();
}
topLimit--;
unsorted = false;
for(int i = 0; i < list.getSize(); i++)
{
int oneData = (Integer) list.find(i).getData();
int twoData = (Integer) list.find(i+1).getData();
if(oneData > twoData)
{
unsorted = true;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment