From 5ae95951627709462f45c0507970ce97e5757323 Mon Sep 17 00:00:00 2001 From: sanaa-duhh Date: Thu, 31 Oct 2024 14:35:49 +0530 Subject: [PATCH 1/3] added bubblesort --- C++/bubbleSort.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/bubbleSort.cpp diff --git a/C++/bubbleSort.cpp b/C++/bubbleSort.cpp new file mode 100644 index 0000000..256a9c8 --- /dev/null +++ b/C++/bubbleSort.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; +void bubbleSort(int arr[], int size) { + for (int step = 0; step < size; ++step) { + for (int i = 0; i < size - step; ++i) { + if (arr[i] > arr[i + 1]) { + int temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + } + } + } +} + +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout << " " << arr[i]; +} + +int main() +{ + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + int N = sizeof(arr) / sizeof(arr[0]); + bubbleSort(arr, N); + cout << "Sorted array: \n"; + printArray(arr, N); + return 0; +} \ No newline at end of file From 88c51e402cc152b6b5cbdb39d5b9b7de4445cf27 Mon Sep 17 00:00:00 2001 From: sanaa-duhh Date: Thu, 31 Oct 2024 17:58:07 +0530 Subject: [PATCH 2/3] added bubblesort --- C++/bubbleSort.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/bubbleSort.cpp b/C++/bubbleSort.cpp index 256a9c8..2135556 100644 --- a/C++/bubbleSort.cpp +++ b/C++/bubbleSort.cpp @@ -1,8 +1,8 @@ -#include +#include using namespace std; void bubbleSort(int arr[], int size) { for (int step = 0; step < size; ++step) { - for (int i = 0; i < size - step; ++i) { + for (int i = 0; i < size - step - 1; ++i) { if (arr[i] > arr[i + 1]) { int temp = arr[i]; arr[i] = arr[i + 1]; From b65ebd4fb2dcb46fe7c9f9cd959bf90a4440161d Mon Sep 17 00:00:00 2001 From: sanaa-duhh Date: Thu, 31 Oct 2024 18:09:58 +0530 Subject: [PATCH 3/3] added insertionsort --- C++/insertionsort.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/insertionsort.cpp diff --git a/C++/insertionsort.cpp b/C++/insertionsort.cpp new file mode 100644 index 0000000..04772b0 --- /dev/null +++ b/C++/insertionsort.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +void insertionSort(int arr[], int n) { + for (int i = 1; i < n; i++) { + int key = arr[i]; + int j = i - 1; + + // 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--; + } + arr[j + 1] = key; + } +} + +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +int main() { + int arr[] = {12, 11, 13, 5, 6}; + int n = sizeof(arr)/sizeof(arr[0]); + + insertionSort(arr, n); + printArray(arr, n); + + return 0; +} \ No newline at end of file