Skip to content

Commit

Permalink
Merge pull request #35 from Skywalker97/master
Browse files Browse the repository at this point in the history
Added interpolation search.
  • Loading branch information
srbcheema1 authored Oct 1, 2017
2 parents 6a72b9b + 21e2332 commit 43105dc
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Searching Algorithms/Interpolation Search
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include<iostream>
using namespace std;


int main(){

int N,x;

cin>>N;
int arr[N];
for(int i=0;i<N;i++)
{
cin>>arr[i];
}

//Taking the number to be searched.
cin>>x;

//Getting first and last index of the array.
int lo = 0, hi = (N - 1);
int flag=0;

//If the element is present in the sorted array, it must be in the range defined by 'hi' and 'lo'.
while (lo <= hi && x >= arr[lo] && x <= arr[hi])
{
// The idea of formula is to return higher value of pos
// when element to be searched is closer to arr[hi], and
// smaller value when closer to arr[lo]
int pos = lo + (((double)(hi-lo) /
(arr[hi]-arr[lo]))*(x - arr[lo]));

if (arr[pos] == x)
{
cout<<pos;
//Number found at pos
flag=1;
}

if (arr[pos] < x)
lo = pos + 1;


else
hi = pos - 1;
}
if(flag == 0)
cout<<-1;
}


55 changes: 55 additions & 0 deletions Sorting Algorithms/Counting_Sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include<iostream>
using namespace std;

int main()
{
int N,x;

cin>>N;
int A[N];
//The elements of the array must not exceed the size of the array.
//This algo is ideally suited for numbers within a range with repetitions.
for(int i=0;i<N;i++)
{
cin>>A[i];
}

// Find the maximum value in A[]
int K = 0;
for(int i=0; i<N; i++) {
K = max(K, A[i]);
}

int Aux[N];
// Initialize the elements of Aux[] with 0
for(int i=0 ; i<=K; i++) {
Aux[i] = 0;
}

// Store the frequencies of each element of A[],
// by mapping its value as the index of Aux[] array
for(int i=0; i<N; i++) {
Aux[A[i]]++;
}

int sortedA[N];
int j = 0;
for(int i=0; i<=K; i++) {
int tmp = Aux[i];
// Aux stores which element occurs how many times,
// Add i in sortedA[] according to the number of times i occured in A[]
while(tmp--) {

sortedA[j] = i;
j++;
}
}
for(int i=0;i<N; i++)
{
cout<<sortedA[i]<<" ";

}



}

0 comments on commit 43105dc

Please sign in to comment.