本文整理了各种算法与数据结构,并给出了C++实现。本文仍在不断更新中,敬请期待。
查找算法
Binary Search
#include <iostream>
using namespace std;
int binary_search(int a[], int l, int r, int key)
{
while (l <= r)
{
int m = l + (r - l) / 2;
if (key == a[m])
return m;
else if (key < a[m])
r = m - 1;
else
l = m + 1;
}
return -1;
}
int main(int argc, char const *argv[])
{
int n, key;
cout << "Enter size of array: ";
cin >> n;
cout << "Enter array elements: ";
int a[n];
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
cout << "Enter search key: ";
cin >> key;
int res = binary_search(a, 0, n - 1, key);
if (res != -1)
cout << key << " found at index " << res << endl;
else
cout << key << " not found" << endl;
return 0;
}
Interpolation Search
#include <iostream>
int InterpolationSearch(int A[], int n, int x)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low]));
if (x == A[mid])
return mid; // Found x, return (exit)
else if (x < A[mid])
high = mid - 1; // X lies before mid
else
low = mid + 1; // x lies after mid
}
return -1;
}
int main()
{
int A[] = {
2, 4, 5, 7, 13, 14, 15, 23};
int x = 17;
int index = InterpolationSearch(A, 8, x); // passed array A inside the InterpolationSearch function
if (index != -1)
std::cout << "Number " << x << " is at " << index;
else
std::cout << "Number " << x << " not found";
}
// randomly set x bcoz array was defined by us , therefore not reasonable for asking input.
// We could have asked for input if array elements were inputed by the user.
Liner Search
#include <iostream>
using namespace std;
int LinearSearch(int *array, int size, int key)
{
for (int i = 0; i < size; ++i)
{
if (array[i] == key)
{
return i;
}
}
return -1;
}
int main()
{
int size;
cout << "\nEnter the size of the Array : ";
cin >> size;
int array[size];
int key;
//Input array
cout << "\nEnter the Array of " << size << " numbers : ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
cout << "\nEnter the number to be searched : ";
cin >> key;
int index = LinearSearch(array, size, key);
if (index != -1)
{
cout << "\nNumber found at index : " << index;
}
else
{
cout << "\nNot found";
}
return 0;
}
Exponential Search
#include <assert.h>
#include <iostream>
#include <string>
using namespaces std;
// Binary Search Algorithm(use by struzik algorithm)
// Time Complexity O(log n) where 'n' is the number of elements
// Worst Time Complexity O(log n)
// Best Time Complexity Ω(1)
// Space Complexity O(1)
// Auxiliary Space Complexity O(1)
template<class Type> inline Type* binary_s(Type *array, size_t size, Type key) {
int32_t lower_index(0), upper_index(size - 1), middle_index;
while (lower_index <= upper_index) {
middle_index = floor((lower_index + upper_index) / 2);
if (*(array + middle_index) < key) lower_index = (middle_index + 1);
else if (*(array + middle_index) > key)upper_index = (middle_index - 1);
else return (array + middle_index);
}
return nullptr;
}
// Struzik Search Algorithm(Exponential)
// Time Complexity O(log i)where i is the position of search key in the list
// Worst Time Complexity O(log i)
// Best Time Complexity Ω(1)
// Space Complexity O(1)
// Auxiliary Space Complexity O(1)
/* Tha algorithm try to search the range where the key should be.
If it has been found we do a binary search there.
The range of the search grows by exponential every time.
If the key is larger than the last element of array,
the start of block(block_front) will be equal to the end of block(block_size)
and the algorithm return null ponter,
every other cases the algoritm return fom the loop. */
template<class Type> Type* struzik_search(Type* array, size_t size, Type key) {
uint32_t block_front(0), block_size = size == 0 ? 0 : 1;
while (block_front != block_size) {
if (*(array + block_size - 1) < key) {
block_front = block_size;
(block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size;
continue;
}
return binary_s<Type>(array + block_front, (block_size - block_front), key);
}
return nullptr;
}
int main() {
// TEST CASES
int *sorted_array = new int[7]{
7, 10, 15, 23, 70, 105, 203};
assert(struzik_search<int>(sorted_array, 7, 0) == nullptr);
assert(struzik_search<int>(sorted_array, 7, 1000) == nullptr);
assert(struzik_search<int>(sorted_array, 7, 50) == nullptr);
assert(struzik_search<int>(sorted_array, 7, 7) == sorted_array);
// TEST CASES
return 0;
}
Hash Search
#include <stdlib.h>
#include<stdio.h>
#define MAX 6 // Determines how much data
#define HASHMAX 5 // Determines the length of the hash table
/**
* Hash Search Algorithm
* Best Time Complexity Ω(1)
* In this algorithm, we use the method of division and reservation remainder to construct the hash function,
* and use the method of chain address to solve the conflict, that is, we link a chain list after the data,
* and store all the records whose keywords are synonyms in the same linear chain list. */
int data[MAX] = {
1, 10, 15, 5, 8, 7}; // test data
typedef struct list {
int key;
struct list * next;
}
node, * link;
node hashtab[HASHMAX];
int counter = 1;
/* int h(int key)
* Mode of hash detection :
* Division method */
int h(int key) {
return key % HASHMAX;
}
/* void create_list(int key)
* The same after the remainder will be added after the same hash header
* To avoid conflict, zipper method is used
* Insert elements into the linked list in the header */
void create_list(int key) {
// Construct hash table
link p, n;
int index;
n = (link) malloc(sizeof(node));
n -> key = key;
n -> next = NULL;
index = h(key);
p = hashtab[index].next;
if (p != NULL) {
n -> next = p;
hashtab[index].next = n;
} else {
hashtab[index].next = n; }
}
/* int hash_search(int key)
* Input the key to be searched, and get the hash header position through the H (int key) function,
* then one-dimensional linear search.
* If found @return element depth and number of searches
* If not found @return -1 */
int hash_search(int key) {
// Hash lookup function
link pointer;
int index;
counter = 0;
index = h(key);
pointer = hashtab[index].next;
printf("data[%d]:", index);
while (pointer != NULL) {
counter++;
printf("data[%d]:", pointer -> key);
if (pointer -> key == key)
return 1;
else
pointer = pointer -> next;
}
return 0;
}
int main() {
link p;
int key, index, i; // Key is the value to be found
index = 0;
// You can write the input mode here
while (index < MAX) {
// Construct hash table
create_list(data[index]);
index++;
}
for (i = 0; i < HASHMAX; i++) {
// Output hash table
printf("hashtab [%d]", i);
printf("\n");
p = hashtab[i].next;
while (p != NULL) {
printf("please int key:");
if (p -> key > 0)
printf("[%d]", p -> key);
p = p -> next;
}
printf("\n");
}
while (key != -1) {
// You can write the input mode here
// test key = 10
key = 10;
if (hash_search(key))
printf("search time = %d\n", counter);
else
printf("no found!\n");
key = -1; // Exit test
/* The test sample is returned as: data[0]:data[5]:data[15]:data[10]:search time = 3
* The search is successful. There are 10 in this set of data */
}
return 0;
}
Median Search
#include<iostream>
#include<math.h>
#include<deque>
#include<stack>
#include<vector>
#include<algorithm>
#include<iterator>
using namespace std;
vector<int>v;
vector<int>s1;
vector<int>s2;
vector<int>s3;
template <class X>
void comp(X x)
{
if(s1.size()>=x && s1.size()+s2.size()<x)
{
cout<<s2[0]<<" is the "<<x+1<<"th element from front";
}
else if(s1.size()>x)
{
sort(s1.begin(),s1.end());
cout<<s1[x]<<" is the "<<x+1<<"th element from front";
}
else if(s1.size()+s2.size()<=x && s3.size()>x)
{
sort(s3.begin(),s3.end());
cout<<s3[x-s1.size()-s2.size()]<<" is the "<<x+1<<"th element from front";
}
else
{
cout<<x+1<<" is invalid location";
}
}
int main()
{
for(int i=0;i<1000;i++)
{
v.push_back(rand()%1000);
}
for(int r:v)
{
cout<<r<<" ";
}
int median=rand()%1000;
cout<<"\nmedian="<<median<<endl;
int avg1,avg2,avg3,sum1=0,sum2=0,sum3=0;
for(int i=0;i<1000;i++)
{
if(v.back()==v[median])
{
avg1=sum1+v.back();
s2.push_back(v.back());
}
else if(v.back()<v[median])
{
avg2=sum2+v.back();
s1.push_back(v.back());
}
else
{
avg3=sum3+v.back();
s3.push_back(v.back());
}
v.pop_back();
}
int x;
cout<<"enter the no. to be searched form begining:- ";
cin>>x;
comp(x-1);
return 0;
}
Search
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
char paragraph;
int main()
{
string paragraph;
cout << "Please enter your paragraph: \n";
getline(cin, paragraph);
cout << "\nHello, your paragraph is:\n " << paragraph << "!\n";
cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n";
if (paragraph.empty())
{
cout << "\nThe paragraph is empty" << endl;
}
else
{
while (true)
{
string word;
cout << "Please enter the word you are searching for: ";
getline(cin, word);
cout << "Hello, your word is " << word << "!\n";
if (paragraph.find(word) == string::npos)
{
cout << word << " does not exist in the sentence" << endl;
}
else
{
cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl
<< endl;
}
system("pause");
}
}
}
Ternary Search
/*
* This is a divide and conquer algorithm.
* It does this by dividing the search space by 3 parts and
* using its property (usually monotonic property) to find
* the desired index.
*
* Time Complexity : O(log3 n)
* Space Complexity : O(1) (without the array)
*/
#include <iostream>
using namespace std;
/*
* The absolutePrecision can be modified to fit preference but
* it is recommended to not go lower than 10 due to errors that
* may occur.
*
* The value of _target should be decided or can be decided later
* by using the variable of the function.
*/
#define _target 10
#define absolutePrecision 10
#define MAX 10000000
int N = 21;
int A[MAX] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10};
/*
* get_input function is to receive input from standard IO
*/
void get_input()
{
// TODO: Get input from STDIO or write input to memory as done above.
}
/*
* This is the iterative method of the ternary search which returns the index of the element.
*/
int it_ternary_search(int left, int right, int A[], int target)
{
while (1)
{
if (left < right)
{
if (right - left < absolutePrecision)
{
for (int i = left; i <= right; i++)
if (A[i] == target)
return i;
return -1;
}
int oneThird = (left + right) / 3 + 1;
int twoThird = (left + right) * 2 / 3 + 1;
if (A[oneThird] == target)
return oneThird;
else if (A[twoThird] == target)
return twoThird;
else if (target > A[twoThird])
left = twoThird + 1;
else if (target < A[oneThird])
right = oneThird - 1;
else
left = oneThird + 1, right = twoThird - 1;
}
else
return -1;
}
}
/*
* This is the recursive method of the ternary search which returns the index of the element.
*/
int rec_ternary_search(int left, int right, int A[], int target)
{
if (left < right)
{
if (right - left < absolutePrecision)
{
for (int i = left; i <= right; i++)
if (A[i] == target)
return i;
return -1;
}
int oneThird = (left + right) / 3 + 1;
int twoThird = (left + right) * 2 / 3 + 1;
if (A[oneThird] == target)
return oneThird;
if (A[twoThird] == target)
return twoThird;
if (target < A[oneThird])
return rec_ternary_search(left, oneThird - 1, A, target);
if (target > A[twoThird])
return rec_ternary_search(twoThird + 1, right, A, target);
return rec_ternary_search(oneThird + 1, twoThird - 1, A, target);
}
else
return -1;
}
/*
* ternary_search is a template function
* You could either use it_ternary_search or rec_ternary_search according to preference.
*/
void ternary_search(int N, int A[], int target)
{
cout << it_ternary_search(0, N - 1, A, target) << '\t';
cout << rec_ternary_search(0, N - 1, A, target) << '\t';
cout << '\n';
}
int main()
{
get_input();
ternary_search(N, A, _target);
return 0;
}
排序算法
BeadSort
// C++ program to implement gravity/bead sort
#include <stdio.h>
#include <string.h>
using namespace std;
#define BEAD(i, j) beads[i * max + j]
// function to perform the above algorithm
void beadSort(int *a, int len)
{
// Find the maximum element
int max = a[0];
for (int i = 1; i < len; i++)
if (a[i] > max)
max = a[i];
// allocating memory
unsigned char beads[max*len];
memset(beads, 0, sizeof(beads));
// mark the beads
for (int i = 0; i < len; i++)
for (int j = 0; j < a[i]; j++)
BEAD(i, j) = 1;
for (int j = 0; j < max; j++)
{
// count how many beads are on each post
int sum = 0;
for (int i=0; i < len; i++)
{
sum += BEAD(i, j);
BEAD(i, j) = 0;
}
// Move beads down
for (int i = len - sum; i < len; i++)
BEAD(i, j) = 1;
}
// Put sorted values in array using beads
for (int i = 0; i < len; i++)
{
int j;
for (j = 0; j < max && BEAD(i, j); j++);
a[i] = j;
}
}
// driver function to test the algorithm
int main()
{
int a[] = {
5, 3, 1, 7, 4, 1, 1, 20};
int len = sizeof(a)/sizeof(a[0]);
beadSort(a, len);
for (int i = 0; i < len; i++)
printf("%d ", a[i]);
return 0;
}
BitonicSort
/* C++ Program for Bitonic Sort. Note that this program
works only when size of input is a power of 2. */
#include <stdio.h>
#include <algorithm.h>
using namespace std;
/*The parameter dir indicates the sorting direction, ASCENDING
or DESCENDING; if (a[i] > a[j]) agrees with the direction,
then a[i] and a[j] are interchanged.*/
void compAndSwap(int a[], int i, int j, int dir)
{
if (dir == (a[i] > a[j]))
swap(a[i], a[j]);
}
/*It recursively sorts a bitonic sequence in ascending order,
if dir = 1, and in descending order otherwise (means dir=0).
The sequence to be sorted starts at index position low,
the parameter cnt is the number of elements to be sorted.*/
void bitonicMerge(int a[], int low, int cnt, int dir)
{
if (cnt > 1)
{
int k = cnt / 2;
for (int i = low; i < low + k; i++)
compAndSwap(a, i, i + k, dir);
bitonicMerge(a, low, k, dir);
bitonicMerge(a, low + k, k, dir);
}
}
/* This function first produces a bitonic sequence by recursively
sorting its two halves in opposite sorting orders, and then
calls bitonicMerge to make them in the same order */
void bitonicSort(int a[], int low, int cnt, int dir)
{
if (cnt > 1)
{
int k = cnt / 2;
// sort in ascending order since dir here is 1
bitonicSort(a, low, k, 1);
// sort in descending order since dir here is 0
bitonicSort(a, low + k, k, 0);
// Will merge wole sequence in ascending order
// since dir=1.
bitonicMerge(a, low, cnt, dir);
}
}
/* Caller of bitonicSort for sorting the entire array of
length N in ASCENDING order */
void sort(int a[], int N, int up)
{
bitonicSort(a, 0, N, up);
}
// Driver code
int main()
{
int a[] = {
3, 7, 4, 8, 6, 2, 1, 5};
int N = sizeof(a) / sizeof(a[0]);
int up = 1; // means sort in ascending order
sort(a, N, up);
printf("Sorted array: \n");
for (int i = 0; i < N; i++)
printf("%d ", a[i]);
return 0;
}
BubbleSort
//Bubble Sort
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
short swap_check = 1;
cout << "Enter the amount of numbers to sort: ";
cin >> n;
vector<int> numbers;
cout << "Enter " << n << " numbers: ";
int num;
//Input
for (int i = 0; i < n; i++)
{
cin >> num;
numbers.push_back(num);
}
//Bubble Sorting
for (int i = 0; (i < n) && (swap_check == 1); i++)
{
swap_check = 0;
for (int j = 0; j < n - 1 - i; j++)
{
if (numbers[j] > numbers[j + 1])
{
swap_check = 1;
swap(numbers[j], numbers[j + 1]);// by changing swap location. I mean, j. If the number is greater than j + 1, then it means the location.
}
}
}
//Output
cout << "\nSorted Array : ";
for (int i = 0; i < numbers.size(); i++)
{
if (i != numbers.size() - 1)
{
cout << numbers[i] << ", ";
}
else
{
cout << numbers[i] << endl;
}
}
return 0;
}
CocktailSelectionSort
#include <iostream>
using namespace std;
//Iterative Version
void CocktailSelectionSort(vector<int> &vec, int low, int high)
{
while (low <= high)
{
int minimum = vec[low];
int minimumindex = low;
int maximum = vec[high];
int maximumindex = high;
for (int i = low; i <= high; i++)
{
if (vec[i] >= maximum)
{
maximum = vec[i];
maximumindex = i;
}
if (vec[i] <= minimum)
{
minimum = vec[i];
minimumindex = i;
}
}
if (low != maximumindex || high != minimumindex)
{
swap(vec[low], vec[minimumindex]);
swap(vec[high], vec[maximumindex]);
}
else
{
swap(vec[low], vec[high]);
}
low++;
high--;
}
}
//Recursive Version
void CocktailSelectionSort(vector<int> &vec, int low, int high)
{
if (low >= high)
return;
int minimum = vec[low];
int minimumindex = low;
int maximum = vec[high];
int maximumindex = high;
for (int i = low; i <= high; i++)
{
if (vec[i] >= maximum)
{
maximum = vec[i];
maximumindex = i;
}
if (vec[i] <= minimum)
{
minimum = vec[i];
minimumindex = i;
}
}
if (low != maximumindex || high != minimumindex)
{
swap(vec[low], vec[minimumindex]);
swap(vec[high], vec[maximumindex]);
}
else
{
swap(vec[low], vec[high]);
}
CocktailSelectionSort(vec, low + 1, high - 1);
}
//main function, select any one of iterative or recursive version
int main()
{
int n;
cout << "Enter number of elements\n";
cin >> n;
std::vector<int> v(n);
cout << "Enter all the elements\n";
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
CocktailSelectionSort(v, 0, n - 1);
cout << "Sorted elements are\n";
for (int i = 0; i < n; ++i)
{
cout << v[i] << " ";
}
return 0;
}
CountingSortString
#include <iostream>
using namespace std;
void countSort(string arr)
{
string output;
int count[256], i;
for (int i = 0; i < 256; i++)
count[i] = 0;
for (i = 0; arr[i]; ++i)
++count[arr[i]];
for (i = 1; i <= 256; ++i)
count[i] += count[i - 1];
for (i = 0; arr[i]; ++i)
{
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
for (i = 0; arr[i]; ++i)
arr[i] = output[i];
cout << "Sorted character array is " << arr;
}
int main()
{
string arr;
cin >> arr;
countSort(arr);
return 0;
}
CountingSort
#include <iostream>
using namespace std;
int Max(int Arr[], int N)
{
int max = Arr[0];
for (int i = 1; i < N; i++)
if (Arr[i] > max)
max = Arr[i];
return max;
}
int Min(int Arr[], int N)
{
int min = Arr[0];
for (int i = 1; i < N; i++)
if (Arr[i] < min)
min = Arr[i];
return min;
}
void Print(int Arr[], int N)
{
for (int i = 0; i < N; i++)
cout << Arr[i] << ", ";
}
int *Counting_Sort(int Arr[], int N)
{
int max = Max(Arr, N);
int min = Min(Arr, N);
int *Sorted_Arr = new int[N];
int *Count = new int[max - min + 1];
for (int i = 0; i < N; i++)
Count[Arr[i] - min]++;
for (int i = 1; i < (max - min + 1); i++)
Count[i] += Count[i - 1];
for (int i = N - 1; i >= 0; i--)
{
Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i];
Count[Arr[i] - min]--;
}
return Sorted_Arr;
}
int main()
{
int Arr[] = {
47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20;
int *Sorted_Arr;
cout << "\n\tOrignal Array = ";
Print(Arr, N);
Sorted_Arr = Counting_Sort(Arr, N);
cout << "\n\t Sorted Array = ";
Print(Sorted_Arr, N);
cout << endl;
return 0;
}
InsertionSort
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "\nEnter the length of your array : ";
cin >> n;
int Array[n];
cout << "\nEnter any " << n << " Numbers for Unsorted Array : ";
//Input
for (int i = 0; i < n; i++)
{
cin >> Array[i];
}
//Sorting
for (int i = 1; i < n; i++)
{
int temp = Array[i];
int j = i - 1;
while (j >= 0 && temp < Array[j])
{
Array[j + 1] = Array[j];
j--;
}
Array[j + 1] = temp;
}
//Output
cout << "\nSorted Array : ";
for (int i = 0; i < n; i++)
{
cout << Array[i] << "\t";
}
return 0;
}
MergeSort
#include <iostream>
using namespace std;
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void show(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << A[i] << "\n";
}
int main()
{
int size;
cout << "\nEnter the number of elements : ";
cin >> size;
int arr[size];
cout << "\nEnter the unsorted elements : ";
for (int i = 0; i < size; ++i)
{
cout << "\n";
cin >> arr[i];
}
mergeSort(arr, 0, size);
cout << "Sorted array\n";
show(arr, size);
return 0;
}
NumericStringSort
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool NumericSort(string a, string b)
{
while (a[0] == '0')
{
a.erase(a.begin());
}
while (b[0] == '0')
{
b.erase(b.begin());
}
int n = a.length();
int m = b.length();
if (n == m)
return a < b;
return n < m;
}
int main()
{
int n;
cout << "Enter number of elements to be sorted Numerically\n";
cin >> n;
vector<string> v(n);
cout << "Enter the string of Numbers\n";
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
sort(v.begin(), v.end());
cout << "Elements sorted normally \n";
for (int i = 0; i < n; i++)
{
cout << v[i] << " ";
}
cout << "\n";
sort(v.begin(), v.end(), NumericSort);
cout << "Elements sorted Numerically \n";
for (int i = 0; i < n; i++)
{
cout << v[i] << " ";
}
return 0;
}
OddEvenSort
#include <iostream>
#include <vector>
using namespace std;
void oddEven(vector<int> &arr, int size)
{
bool sorted = false;
while (!sorted)
{
sorted = true;
for (int i = 1; i < size - 1; i += 2) //Odd
{
if (arr[i] > arr[i + 1])
{
swap(arr[i], arr[i + 1]);
sorted = false;
}
}
for (int i = 0; i < size - 1; i += 2) //Even
{
if (arr[i] > arr[i + 1])
{
swap(arr[i], arr[i + 1]);
sorted = false;
}
}
}
}
void show(vector<int> A, int size)
{
int i;
for (i = 0; i < size; i++)
cout << A[i] << "\n";
}
int main()
{
int size, temp;
cout << "\nEnter the number of elements : ";
cin >> size;
vector<int> arr;
cout << "\nEnter the unsorted elements : \n";
for (int i = 0; i < size; ++i)
{
cin >> temp;
arr.push_back(temp);
}
oddEven(arr, size);
cout << "Sorted array\n";
show(arr, size);
return 0;
}
QuickSort
#include <iostream>
using namespace std;
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j < high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int p = partition(arr, low, high);
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
void show(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << "\n";
}
// Driver program to test above functions
int main()
{
int size;
cout << "\nEnter the number of elements : ";
cin >> size;
int arr[size];
cout << "\nEnter the unsorted elements : ";
for (int i = 0; i < size; ++i)
{
cout << "\n";
cin >> arr[i];
}
quickSort(arr, 0, size);
cout << "Sorted array\n";
show(arr, size);
return 0;
}
RadixSort
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
using namespace std;
void radixsort(int a[], int n)
{
int count[10];
int output[n];
memset(output, 0, sizeof(output));
memset(count, 0, sizeof(count));
int max = 0;
for (int i = 0; i < n; ++i)
{
if (a[i] > max)
{
max = a[i];
}
}
int maxdigits = 0;
while (max)
{
maxdigits++;
max /= 10;
}
for (int j = 0; j < maxdigits; j++)
{
for (int i = 0; i < n; i++)
{
int t = pow(10, j);
count[(a[i] % (10 * t)) / t]++;
}
int k = 0;
for (int p = 0; p < 10; p++)
{
for (int i = 0; i < n; i++)
{
int t = pow(10, j);
if ((a[i] % (10 * t)) / t == p)
{
output[k] = a[i];
k++;
}
}
}
memset(count, 0, sizeof(count));
for (int i = 0; i < n; ++i)
{
a[i] = output[i];
}
}
}
void print(int a[], int n)
{
for (int i = 0; i < n; ++i)
{
cout << a[i] << " ";
}
cout << endl;
}
int main(int argc, char const *argv[])
{
int a[] = {
170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(a) / sizeof(a[0]);
radixsort(a, n);
print(a, n);
return 0;
}
SelectionSort
#include <iostream>
using namespace std;
int main()
{
int Array[6];
cout << "\nEnter any 6 Numbers for Unsorted Array : ";
//Input
for (int i = 0; i < 6; i++)
{
cin >> Array[i];
}
//Selection Sorting
for (int i = 0; i < 6; i++)
{
int min = i;
for (int j = i + 1; j < 6; j++)
{
if (Array[j] < Array[min])
{
min = j; //Finding the smallest number in Array
}
}
int temp = Array[i];
Array[i] = Array[min];
Array[min] = temp;
}
//Output
cout << "\nSorted Array : ";
for (int i = 0; i < 6; i++)
{
cout << Array[i] << "\t";
}
}
ShellSort
#include <iostream>
using namespace std;
int main()
{
int size = 10;
int array[size];
// Input
cout << "\nHow many numbers do want to enter in unsorted array : ";
cin >> size;
cout << "\nEnter the numbers for unsorted array : ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
// Sorting
for (int i = size / 2; i > 0; i = i / 2)
{
for (int j = i; j < size; j++)
{
for (int k = j - i; k >= 0; k = k - i)
{
if (array[k] < array[k + i])
{
break;
}
else
{
int temp = array[k + i];
array[k + i] = array[k];
array[k] = temp;
}
}
}
}
// Output
cout << "\nSorted array : ";
for (int i = 0; i < size; ++i)
{
cout << array[i] << "\t";
}
return 0;
}
SlowSort
#include <iostream>
using namespace std;
void SlowSort(int a[], int i, int j)
{
if (i >= j)
return;
int m = i + (j - i) / 2; //midpoint, implemented this way to avoid overflow
int temp;
SlowSort(a, i, m);
SlowSort(a, m + 1, j);
if (a[j] < a[m])
{
temp = a[j]; //swapping a[j] & a[m]
a[j] = a[m];
a[m] = temp;
}
SlowSort(a, i, j - 1);
}
//Sample Main function
int main()
{
int size;
cout << "\nEnter the number of elements : ";
cin >> size;
int arr[size];
cout << "\nEnter the unsorted elements : ";
for (int i = 0; i < size; ++i)
{
cout << "\n";
cin >> arr[i];
}
SlowSort(arr, 0, size);
cout << "Sorted array\n";
for (int i = 0; i < size; ++i)
{
cout << arr[i] << " ";
}
return 0;
}
TimSort
#include <iostream>
using namespace std;
const int RUN = 32;
// this function sorts array from left index to to right index which is of size atmost RUN
void insertionSort(int arr[], int left, int right)
{
for (int i = left + 1; i <= right; i++)
{
int temp = arr[i];
int j = i - 1;
while (arr[j] > temp && j >= left)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}
// merge function merges the sorted runs
void merge(int arr[], int l, int m, int r)
{
// original array is broken in two parts, left and right array
int len1 = m - l + 1, len2 = r - m;
int left[len1], right[len2];
for (int i = 0; i < len1; i++)
left[i] = arr[l + i];
for (int i = 0; i < len2; i++)
right[i] = arr[m + 1 + i];
int i = 0;
int j = 0;
int k = l;
// after comparing, we merge those two array in larger sub array
while (i < len1 && j < len2)
{
if (left[i]