-
Notifications
You must be signed in to change notification settings - Fork 302
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
shell_sort.cpp Adds Shell Sort Algorithm
Closes #270
- Loading branch information
1 parent
b993b87
commit eeb228c
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
#include <iostream> | ||
|
||
using std::cout; | ||
|
||
void insertion_sort(int a[], int a_size) { | ||
int i = 0; | ||
while (i < a_size) { | ||
int j = i; | ||
while (j > 0 && a[j-1] > a[j]) { | ||
// swap | ||
int temp = a[j-1]; | ||
a[j-1] = a[j]; | ||
a[j] = temp; | ||
j--; | ||
} | ||
i++; | ||
} | ||
|
||
cout << "After insertion sort: "; | ||
for (int i = 0; i < a_size; i++) { | ||
cout << a[i] << " "; | ||
} | ||
cout << std:: endl; | ||
} | ||
|
||
void shell_sort(int a[], int a_size) { | ||
int gap = 1; | ||
while (gap < a_size/3) { | ||
gap = gap * 3 + 1; //calcutale biggest gap to start with. | ||
} | ||
|
||
while (gap > 0) { | ||
for (int i = 0; i < a_size - gap; i++) { | ||
if (a[i] > a[i + gap]) { | ||
// swap | ||
int temp = a[i]; | ||
a[i] = a[i + gap]; | ||
a[i + gap] = temp; | ||
} | ||
} | ||
gap = (gap - 1) / 3; | ||
} | ||
|
||
cout << "After shell sort: "; | ||
for (int i = 0; i < a_size; i++) { | ||
cout << a[i] << " "; | ||
} | ||
cout << std:: endl; | ||
|
||
insertion_sort(a, a_size); | ||
} | ||
|
||
int main(void) { | ||
int a[8] = {3, 7, 4, 9, 5, 2, 6, 1}; | ||
int a_size = sizeof(a) / sizeof(a[0]); | ||
|
||
shell_sort(a, a_size); | ||
|
||
for (int i = 0; i < a_size; i++) { | ||
cout << a[i] << " "; | ||
} | ||
} |
eeb228c
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Comment on eeb228c.
There are 71 results for the section all.cpp. They have been shortened and will not be shown inline because they are more than 10.
Until GitMate provides an online UI to show a better overview, you can run coala locally for more details.