Codes For A Lot of Things
Codes For A Lot of Things
(1) Bubblesort
#include <iostream>
// Move elements of arr[0..i-1], that are greater than key, to one position
ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
(3) Merge sort
#include <iostream>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
cout << "Sorted array is: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
(4) Quicksort
#include <iostream>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array is: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
(5) Stacks #LIFO
#include <iostream>
using namespace std;
// Define the maximum size of the stack
const int MAX_SIZE = 4;
class Stack {
private:
int arr[MAX_SIZE];
int top;
public:
// Constructor
Stack() {
top = -1;
}
int main() {
Stack myStack;
int numElements;
cout << "Enter the number of elements you want to push into the stack: ";
cin >> numElements;
int element;
for (int i = 0; i < numElements; ++i) {
cout << "Enter element " << i + 1 << ": ";
cin >> element;
myStack.push(element);
}
return 0;
}
(6) Queue
#include <iostream>
using namespace std;
// Define the maximum size of the queue
const int MAX_SIZE = 100;
class Queue {
private:
int arr[MAX_SIZE];
int front, rear;
public:
// Constructor
Queue() {
front = -1;
rear = -1;
}
int main() {
Queue myQueue;
int numElements;
cout << "Enter the number of elements you want to enqueue into the queue: ";
cin >> numElements;
int element;
for (int i = 0; i < numElements; ++i) {
cout << "Enter element " << i + 1 << ": ";
cin >> element;
myQueue.enqueue(element);
}
return 0;
}