FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
competitive-programming/Sorting/Gnome-Sort.cpp at master · kothariji/competitive-programming · GitHub
kothariji
/
competitive-programming
Public
Notifications
You must be signed in to change notification settings
Fork
500
Star
704
Code
Issues
1
Pull requests
2
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
competitive-programming
/
Sorting
/
Gnome-Sort.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
60 lines (56 loc) · 1.57 KB
Breadcrumbs
competitive-programming
/
Sorting
/
Gnome-Sort.cpp
Copy path
File metadata and controls
60 lines (56 loc) · 1.57 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
Program of Gnome Sorting works well for partially sorted arrays.
#
include
<
iostream
>
using
namespace
std
;
//
A function to sort the algorithm using gnome sort
void
gnomeSortFunc
(
int
*array,
int
n)
{
//
Intialising the index variable to 0
int
i =
0
;
//
Checking if index value is less than size of array
while
(i < n){
if
(i ==
0
){
i++;
}
//
checks if present element is larger than previous element
//
if larger then goes to right of array increments index
if
(array[i] >= array[i -
1
]){
i++;
}
//
else if present element is smaller then
//
it swaps the two elements and goes to left decrements index value
else
{
swap
(array[i], array[i -
1
]);
i--;
}
}
return
;
}
//
A utility function ot print an array of size n
void
printSortedArray
(
int
array[],
int
size)
{
cout <<
"
\n
Sorted Numbers after applying Gnome sort :
"
;
for
(
int
i =
0
; i < size; i++){
cout<<array[i]<<
"
"
;
}
cout<<
"
\n\n
"
;
}
//
Driver program to test above functions.
int
main
()
{
cout<<
"
---------------------------------------------------
\n
"
;
cout<<
"
------------ Gnome Sort ----------
\n
"
;
cout<<
"
---------------------------------------------------
\n
"
;
int
n;
cout<<
"
Enter the number of elements :
"
;
cin>>n;
int
*array =
new
int
[n];
cout<<
"
\n
Enter the elements :
"
;
for
(
int
i=
0
;i<n;i++){
cin>>array[i];
}
gnomeSortFunc
(array,n);
printSortedArray
(array,n);
return
0
;
}
/*
Time Complexity is O(n^2)
since the variable in loop in getting incremented and decremented also
*/
Back
|
FazBrowse Home
|
New Git URL