Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- ** Jessica Wong
- */
- import java.util.*;
- public class Main {
- public static void main(String[] args) {
- int array[] = {3,4,1,2,5};
- int array2[] = {3,4,1,2,5};
- int array3[] = {3,4,1,2,5};
- List<Integer> list = new ArrayList<>();
- for (int i = 0; i < 5; i++)
- {
- list.add((int)(Math.random()*10));
- }
- arrayPrint(array);
- arraySort_bubble(array);
- arrayPrint(array);
- arraySort_selection(array2);
- arrayPrint(array2);
- arraySort_insertion(array3);
- arrayPrint(array3);
- System.out.println("Unsorted List: " + list);
- listSort_selection(list);
- System.out.println("Sorted List: " + list);
- }
- public static void arraySort_bubble(int[] sort)
- {
- for (int x = 0; x < sort.length; x++)
- {
- for (int y = 0; y < sort.length-1; y++)
- {
- int temp = Math.min(sort[y], sort[y+1]);
- sort[y] = Math.max(sort[y], sort[y+1]);
- sort[y+1] = temp;
- }
- }
- }
- public static void arraySort_selection(int[] sort)
- {
- for (int x = 0; x < sort.length; x++)
- {
- int maxPos = x;
- int max = sort[x];
- for (int y = x+1; y < sort.length; y++)
- {
- if (sort[y] > max)
- {
- max = sort[y];
- maxPos = y;
- }
- }
- sort[maxPos] = sort[x];
- sort[x] = max;
- }
- }
- public static void arraySort_insertion(int[] a)
- {
- int itemToInsert, j;
- boolean keepGoing;
- //On kth pass, insert item k into its correct position among the first k items in the array
- for(int k = 1; k < a.length; k++)
- {
- //Go backwards through the list, looking for the slot to insert a[k]
- itemToInsert = a[k];
- j = k - 1;
- keepGoing = true;
- while((j >= 0) && keepGoing)
- {
- if (itemToInsert > a[j] )
- {
- a[j + 1] = a[j]; //Salient feature
- j--;
- if(j == -1) //special case for inserting an item at [0]
- a[0] = itemToInsert;
- }
- else //Upon leaving loop, j + 1 is the index where itemToInsert belongs
- {
- keepGoing = false;
- a[j + 1] = itemToInsert;
- }
- }
- }
- }
- public static void arrayPrint(int[] arr)
- {
- for (int x = 0; x < arr.length; x++)
- {
- if (x == arr.length-1)
- {
- System.out.println(arr[x]);
- }
- else
- {
- System.out.print(arr[x] + ", ");
- }
- }
- }
- public static void listSort_selection(List<Integer> num)
- {
- for (int x = 0; x < num.size(); x++)
- {
- int minPos = x;
- int min = num.get(x);
- for (int y = x+1; y < num.size(); y++)
- {
- if (num.get(y) < min)
- {
- min = num.get(y);
- minPos = y;
- }
- }
- num.set(minPos, num.get(x));
- num.set(x, min);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement