Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gnome sort #288

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Arrays/Prefix-Sum-Array
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// A C++ program to find if there is a zero sum
// subarray
#include <bits/stdc++.h>
using namespace std;

bool subArrayExists(int arr[], int n)
{
unordered_set<int> sumSet;

// Traverse through array and store prefix sums
int sum = 0;
for (int i = 0 ; i < n ; i++)
{
sum += arr[i];

// If prefix sum is 0 or it is already present
if (sum == 0 || sumSet.find(sum) != sumSet.end())
return true;

sumSet.insert(sum);
}
return false;
}

// Driver code
int main()
{
int arr[] = {-3, 2, 3, 1, 6};
int n = sizeof(arr)/sizeof(arr[0]);
if (subArrayExists(arr, n))
cout << "Found a subarray with 0 sum";
else
cout << "No Such Sub Array Exists!";
return 0;
}
41 changes: 41 additions & 0 deletions Sorting/GnomeSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <iostream>
using namespace std;

// A function to sort the algorithm using gnome sort
void gnomeSort(int arr[], int n)
{
int index = 0;

while (index < n) {
if (index == 0)
index++;
if (arr[index] >= arr[index - 1])
index++;
else {
swap(arr[index], arr[index - 1]);
index--;
}
}
return;
}

// A utility function ot print an array of size n
void printArray(int arr[], int n)
{
cout << "Sorted sequence after Gnome sort: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
}

// Driver program to test above functions.
int main()
{
int arr[] = { 34, 2, 10, -9 };
int n = sizeof(arr) / sizeof(arr[0]);

gnomeSort(arr, n);
printArray(arr, n);

return (0);
}