Skip to main content

Posts

Showing posts with the label Sorting Algorithm

insertion Sort Program in java

 insertion Sort Program in java Code: import java.util.*; import java.lang.*; import java.io.*; //Insertion Sort class Test{ public static void main(String[] args){ int[] arr = {7,2,4,1,5,3}; insertion(arr); for(int i : arr){ System.out.print(i+" "); } } public static void insertion(int[] arr){ for(int i=1;i<arr.length;i++){ int hole = i; int val = arr[i]; while(hole>0 && arr[hole-1]>val){ arr[hole] = arr[hole-1]; hole--; } arr[hole] = val; } } }

Bubble Sort Program in java

 Bubble Sort Program in java Code:: import java.util.*; import java.lang.*; import java.io.*; //Bubble Sort class Test{ public static void main(String[] args){ int[] arr = {2,7,4,1,5,3}; bubble(arr); for(int i : arr){ System.out.print(i+" "); } } public static void bubble(int[] arr){ for(int i=0;i<arr.length;i++){ //the last val is at its correct Position for(int j=0;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ //swap int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } } Optimized code if the right part of the array is sorted code: import java.util.*; import java.lang.*; import java.io.*; //Bubble Sort class Test{ public static void main(String[] args){ int[] arr = {2,7,4,1,5,3}; bubble(arr); for(int i : arr){ System.out.print(i+" "); } } public static void bubble(int[] arr){ for(int i=0;i<arr.length;i++){ int swap = 0; for(int j=0;j<...

Merge Sort Program in java

 Merge Sort Program in java Code :: import java.util.*; import java.lang.*; import java.io.*; class Test { public static void main(String[] args){ int[] arr = {7,2,4,1,5,3}; mergeSort(arr); for(int i : arr){ System.out.print(i+" "); } } public static void mergeSort(int[] arr){ int n = arr.length; if(n<2){ return; } int mid = n/2; int[] left = new int[mid]; int[] right = new int[n-mid]; for(int i=0;i<mid;i++){ left[i] = arr[i]; } for(int i=mid;i<n;i++){ right[i-mid] = arr[i]; } mergeSort(left); mergeSort(right); merge(left,right,arr); } public static void merge(int[] left,int[] right,int[] arr){ int i = 0; int j = 0; int k = 0; while(i<left.length && j<right.length){ if(left[i]<right[j]){ arr[k] = left[i]; i++; }else{ arr[k] = right[j]; j++; } k++; } while(i!=left.length){ arr[k] = left[i]; i++; k++; } wh...