Topic: Sorting
Questions Successfully Completed: 2
1) Insertion Sort | Easy |
2) Selection Sort | Easy |
Insertion Sort
Time Complexity : O(n2)
Space Complexity : O(1)
Question
Input: N = 5 arr[] = { 4, 1, 3, 9, 7} Output: 1 3 4 7 9
static void insert(int arr[],int i)
{
int key = arr[i];
int j = i-1;
while (j>=0 && key<arr[j]){
arr[j+1] = arr[j];
j--;
}
arr[j+1]=key;
}
public void insertionSort(int arr[], int n)
{
for(int i=1;i<n;i++){
insert(arr,i);
}
}
Selection Sort
Time Complexity : O(n2)
Space Complexity : O(1)
public static void selection(int[] arr, int n){
int k=0;
for(int i=0;i<n-1;i++){ // n-1 because in last pass last element will already be sorted.
k=i;
for(int j=i+1;j<n;j++){
if(arr[j]<arr[k]){
k=j;
}
}
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args) {
int[] arr = {8,5,3,1,9};
selection(arr,arr.length);
}
Thank you for Reading! :)