The following programs are bubble sorting, selection sorting and insertion sorting. As most of the programs online or in books are with Array
s and not ArrayList
, I am unsure if they are correct.
BubbleSort
:
public class BubbleSort {
List<Integer> unsortedList;
private BubbleSort() {
unsortedList = new ArrayList<Integer>();
unsortedList.add(0, 6);
unsortedList.add(1, 3);
unsortedList.add(2, 7);
unsortedList.add(3, 4);
unsortedList.add(4, 2);
unsortedList.add(5, 3);
unsortedList.add(6, 8);
}
private void sortData() {
ArrayList<Integer> tempList = (ArrayList<Integer>) this.unsortedList;
int size = unsortedList.size();
int counter = size;
do {
for (int i = 0; i < size-1; i++) {
if (unsortedList.get(i) > unsortedList.get(i + 1)) {
Integer temp1= unsortedList.get(i + 1);
Integer temp2= unsortedList.get(i);
unsortedList.set(i,temp1);
unsortedList.set(i+1,temp2);
}
}
size = size - 1;
} while (size != 1);
}
public static void main(String arg[]) {
BubbleSort obj = new BubbleSort();
obj.sortData();
for(Integer i:obj.unsortedList){
System.out.println(i);
}
}}
SelectionSort
:
public class SelectionSort {
List<Integer> unsortedList;
private SelectionSort() {
unsortedList = new ArrayList<Integer>();
unsortedList.add(0, 16);
unsortedList.add(1, 3);
unsortedList.add(2, 7);
unsortedList.add(3, 4);
unsortedList.add(4, 12);
unsortedList.add(5, 3);
unsortedList.add(6, 8);
unsortedList.add(7, 18);
unsortedList.add(8, 81);
unsortedList.add(9, 2);
}
public void sortData() {
int totalPass = unsortedList.size();
int listLength = totalPass;
for (int i = 0; i <= totalPass - 1; i++) {
int pointerSmallPosition=i;
for (int j = i; j < listLength-1; j++) {
if (unsortedList.get(pointerSmallPosition) > unsortedList.get(j + 1)) {
pointerSmallPosition=j + 1;
}
}
int temp1= unsortedList.get(i);
int temp2= unsortedList.get(pointerSmallPosition);
unsortedList.set(i,temp2);
unsortedList.set(pointerSmallPosition,temp1);
}
}
public static void main(String arg[]) {
SelectionSort obj = new SelectionSort();
obj.sortData();
for (Integer i : obj.unsortedList) {
System.out.println(i);
}
}}
InsertionSort
:
public class InsertionSort {
List<Integer> unsortedList;
public InsertionSort(){
unsortedList = new ArrayList<Integer>();
unsortedList.add(0, 6);
unsortedList.add(1, 3);
unsortedList.add(2, 7);
unsortedList.add(3, 4);
unsortedList.add(4, 2);
unsortedList.add(5, 3);
unsortedList.add(6, 8);
}
public static void main(String arg[]){
InsertionSort obj=new InsertionSort();
obj.sortData();
for(Integer i:obj.unsortedList){
System.out.println(i);
}
}
private void sortData() {
int size = unsortedList.size();
int sortedSize=0;
for(int i=1;i<size-1;i++){
int j=i;
do{
if(unsortedList.get(j)<unsortedList.get(j-1)){
int small=unsortedList.get(j);
int large=unsortedList.get(j-1);
unsortedList.set(j-1, small);
unsortedList.set(j, large);
}
j--;
}while(j>sortedSize);
}}}