Skip to content

Instantly share code, notes, and snippets.

@m-primo
Last active November 9, 2020 02:08
Show Gist options
  • Save m-primo/27cdf006fbdf44c2f690fbd6d4769658 to your computer and use it in GitHub Desktop.
Save m-primo/27cdf006fbdf44c2f690fbd6d4769658 to your computer and use it in GitHub Desktop.
Some Sorts Implementation in C++
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void showArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << ", ";
}
cout << endl;
}
void bubbleSort(int arr[], int size) {
for(int i = 0; i < size - 1; i++) {
for(int j = 0; j < size - 1; j++) {
if(arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
void selectionSort(int arr[], int size) {
for(int i = 0; i < size - 1; i++) {
for(int j = i + 1; j < size; j++) {
if(arr[i] > arr[j]) {
swap(arr[i], arr[j]);
}
}
}
}
void insertionSort(int arr[], int size) {
for(int i = 1; i < size; i++) {
for(int j = i; j >= 1; j--) {
if(arr[j] < arr[j - 1]) {
swap(arr[j], arr[j - 1]);
} else break;
}
}
}
void countSort(int arr[],int size) {
int k = 0;
int *arr = new int[size];
for(int i = 1; i <= size; i++) {
if(arr[i] > k) k = arr[i];
}
int arr_index[k], output[size];
for(int i = 0; i < k+1; i++) arr_index[i] = 0;
for(int j = 1; j <= size; j++) arr_index[arr[j]]++;
for(int i = 1; i <= k; i++) arr_index[i] += arr_index[i-1];
for(int j = size; j >= 1; j--) {
output[arr_index[arr[j]]] = arr[j];
arr_index[arr[j]]--;
}
}
int main() {
int arr[] = {45,23,35,422,51,74,755,154,1,22,10};
int size = sizeof(arr) / sizeof(int);
showArray(arr, size);
//sort function here
showArray(arr, size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment