Yes code

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.1 kB
2
Indexable
Never
package exercises;
//insertion
public class Insertion {
	public static void main(String[] args) {
		int[] num = {2, 1 , 609, 9 ,3};
		int temp;
		
		for (int i = 1; i < num.length; i++) {
			for (int y = 0; y < i; y++) {
				if (num[i] <= num[y]) {
					temp = num[i];
					
					for (int z = i; z > y; z--) {
						num[z] = num[z-1];
						
					}
					
					num[y] = temp;
				}
				
			}
		}
		
		for (int i = 0; i < num.length; i++) {
			System.out.println(num[i]);
		}
			}
}



//selection sort
package exercises;

public class SelectionSort {
	public static void main(String[] args) {
		int[] arr = {2, 1, 9, 4, 6};
		int element = 0, temp = 0;
		for (int i = 0; i <(arr.length - 1); i++) {
			int lowNum = arr[i];
			element = i;
			for (int k = (i+1); k < arr.length; k++) 
			{
				//keep assigning the lower value to lownum, so when the k loop loops, it will keep getting the lower num
				if (lowNum >= arr[k]) {
					lowNum = arr[k];
					element = k;
				}
			}
			temp = arr[i];
			arr[i] = arr[element];
			arr[element] = temp;
		
		
	}
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
}
}

//bubble sort

package exercises;

import javax.swing.JOptionPane;

public class BubbleSort {
	public static void main(String[] args) {
		int arrSize = Integer.parseInt(JOptionPane.showInputDialog("Show number of arrya"));
		int num[] = new int[arrSize];
		for (int i = 0; i < arrSize; i++) {
			num[i] = Integer.parseInt(JOptionPane.showInputDialog("Input number " + (i+1)));
		}
		BubbleSort.bubbleSort(num);
		
	}
	
	public static void bubbleSort(int num[]) {
		//n-1 is amount of times needing to parse
		int lengthArr = num.length;
		for (int x = 0; x < (num.length -1); x++) {
			for (int i = 0; i < (lengthArr -1); i++) {
				if (num[i] > num[i+1]) {
					int smallerNum = num[i+1];
					int biggerNum	= num[i];
					num[i] = smallerNum;
					num[i+1] = biggerNum;
					
				}
//				lengthArr =-1;
			}
		}
		for (int y = 0; y < num.length; y++) {
			System.out.println(num[y]);
		}
	}

}