Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b782f99

Browse files
fix insertionSort
1 parent c1db367 commit b782f99

File tree

1 file changed

+4
-3
lines changed
  • src/main/java/ir/sk/algorithm/others

1 file changed

+4
-3
lines changed

‎src/main/java/ir/sk/algorithm/others/Sort.java‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,18 +111,19 @@ public static void selectionSort(int[] array) {
111111
@Stability
112112
public static void insertionSort(int[] array) {
113113
for (int i = 1; i < array.length; i++) {
114+
int key = array[i];
114115
int j = i - 1;
115116

116117
/* Move elements of arr[0..i-1], that are
117118
greater than key, to one position ahead
118119
of their current position
119120
searching and shift at once */
120-
while (j >= 0 && array[j] > array[i]) {
121+
while (j >= 0 && array[j] > key) {
121122
// using rotate by condition(array[j] > key), no swap, since shifting has better performance than swap
122123
array[j + 1] = array[j];
123-
j = j - 1;
124+
j -= 1;
124125
}
125-
array[j + 1] = array[i];
126+
array[j + 1] = key;
126127
}
127128
}
128129

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /