I will update all the sorting technices which help for students.
All examples I am refer: 2 3 4 5 1
1) Try to understand swap the number: 5 1
int[] arr = { 5, 1 }; int temp = 0, j = 1; if(!(arr[j-1] < arr[j])){ // Needs 5 < 1 no then temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; }
Hope all people know this one.
Insertion Sort:
please refer: https://www.java2novice.com/java-sorting-algorithms/insertion-sort/
My Style: In the insertion sort every pass we are checking sorting from last to first in the inner loop
Ex: 2 3 4 5 1
i=0, inner loop:
2 3 4 5 1 3 < 2 if condition fail skip the swap
i=2,j=2
4 < 3 if condition fail skip the swap
3 < 2 if condition fail skip the swap
i=3,j=3,
5 < 4 if condition fail skip the swap
4 < 3 if condition fail skip the swap
3 < 2 if condition fail skip the swap
i=4,j=4
2 3 4 5 1 1 < 5 yes swap them
2 3 4 1 5 1 < 4 yes swap them
2 3 1 4 5 1 < 3 yes swap them
2 1 3 4 5 1 < 2 yes swap them
1 2 3 4 5
algorithm:
for (int i = 0; i < arr.length; i++) { for(int j = i ; j > 0 ; j--){ if(!(arr[j-1] < arr[j])){ temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } } }
In the insertion sort we start from last to first style, remember this
All examples I am refer: 2 3 4 5 1
1) Try to understand swap the number: 5 1
int[] arr = { 5, 1 }; int temp = 0, j = 1; if(!(arr[j-1] < arr[j])){ // Needs 5 < 1 no then temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; }
Hope all people know this one.
Insertion Sort:
please refer: https://www.java2novice.com/java-sorting-algorithms/insertion-sort/
My Style: In the insertion sort every pass we are checking sorting from last to first in the inner loop
Ex: 2 3 4 5 1
i=0, inner loop:
for
(
int
j = i ; j >
0
; j--), here from last to first means j = 2 it will
loop
until
j > 0
in i = 0; j =0 condition fail here j > 0
i=1,j=1 2 3 4 5 1 3 < 2 if condition fail skip the swap
i=2,j=2
4 < 3 if condition fail skip the swap
3 < 2 if condition fail skip the swap
i=3,j=3,
5 < 4 if condition fail skip the swap
4 < 3 if condition fail skip the swap
3 < 2 if condition fail skip the swap
i=4,j=4
2 3 4 5 1 1 < 5 yes swap them
2 3 4 1 5 1 < 4 yes swap them
2 3 1 4 5 1 < 3 yes swap them
2 1 3 4 5 1 < 2 yes swap them
1 2 3 4 5
algorithm:
for (int i = 0; i < arr.length; i++) { for(int j = i ; j > 0 ; j--){ if(!(arr[j-1] < arr[j])){ temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } } }
In the insertion sort we start from last to first style, remember this
for
(
int
j = i ; j >
0
; j--).
Time Complexity : Average case O(n2), Wrost Case O(n2)
No comments:
Post a Comment