0% found this document useful (0 votes)
6 views2 pages

Java Sorting Algorithms Explained

The document contains Java implementations of several sorting algorithms: bubble sort, selection sort, insertion sort, and merge sort. Each algorithm is defined in a method, demonstrating different approaches to sorting an array of integers. The merge sort algorithm is implemented using a divide-and-conquer strategy, recursively dividing the array and merging the sorted halves.

Uploaded by

gsashishemail
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Java Sorting Algorithms Explained

The document contains Java implementations of several sorting algorithms: bubble sort, selection sort, insertion sort, and merge sort. Each algorithm is defined in a method, demonstrating different approaches to sorting an array of integers. The merge sort algorithm is implemented using a divide-and-conquer strategy, recursively dividing the array and merging the sorted halves.

Uploaded by

gsashishemail
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

```java

public static void bubbleSort(int[] arr){


// n-1
for(int pass=0;pass<[Link]-1;pass++){
// i i+1
for(int bubble=0;bubble<[Link]-1-pass;bubble++){
if(arr[bubble]>arr[bubble+1]){
int helper=arr[bubble];
arr[bubble]=arr[bubble+1];
arr[bubble+1]=helper;
}
}
}
}
// on^2
public static void selectionSort(int[] arr){
for(int i=0;i<[Link];i++){
int minIndex=i;
for(int j=i+1;j<[Link];j++){
if(arr[minIndex]>arr[j]){
minIndex=j;
}
}
int helper=arr[minIndex];
arr[minIndex]=arr[i];
arr[i]=helper;
}
}

public static void insertionSort(int[] arr){


for(int i=1;i<[Link];i++){
for(int j=i-1;j>0;j--){
if(arr[i]<arr[j]){
// swap
int helper=arr[i];
arr[i]=arr[j];
arr[j]=arr[i];
}
}
}
}

public static void merge(int[] arr,int low,int mid,int high){


int[] res=new int[high-low+1];
int i=low,j=mid+1;
int k=0;
while(i<=mid&&j<=high){
if(arr[i]<arr[j]){
res[k]=arr[i];
i++;
}else{
res[k]=arr[j];
j++;
}
k++;
}
while(i<=mid){
res[k]=arr[i];
i++;
k++;
}
while(j<=high){
res[k]=arr[j];
j++;
k++;
}

for(int pass=0;pass<[Link];pass++)
arr[low+pass]=res[pass];
}
public static void divide(int[] arr,int start,int end){

if(start==end) return;
int mid=start+(end-start)/2;
divide(arr,start,mid);
divide(arr,mid+1,end);
merge(arr,start,mid,end);

}
```

You might also like