0% found this document useful (0 votes)
2 views

Lecture 2 Algorithms-1

Uploaded by

fasterff06
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 2 Algorithms-1

Uploaded by

fasterff06
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Lecture 2.

Quadratic sorts
Let's look at three quadratic sorting algorithms - insertion sort,
selection sort, and bubble sort
1. Insertion Sort
How it works:
Start with the first element of the array, assuming it is already sorted.
Take the next element and insert it into the correct place in the sorted
part of the array.
Repeat this process for all elements of the array.
C++ code with explanation:

**Explanation:**
- We start with the second element of the array, assuming that the first
element is already sorted.
- In the `while` loop, we shift the array elements to the right until we
find a position to insert the current element (key).
- Once the correct position is found, we insert the key at that location.

2. Selection Sort

How it works:
- We look for the minimum element in the array and move it to the
beginning.
- Then we look for the minimum element in the rest of the array and
move it to the next position.
- We repeat the process for all elements of the array.
**Explanation:**

- We go through the array and find the minimum element in the


unsorted part.
- Swap it with the first element of this part.
- Repeat the process for each position, thereby gradually moving the
minimum elements to the beginning of the array.

3. Bubble Sort

How it works:
- We go through the array, comparing adjacent elements, and swap
them if they are in the wrong order.
- After each iteration, the largest element "floats" to the end of the
array.
- Repeat the process until the array is completely sorted.

Explanation:

- Each pass through the array compares adjacent elements.


- If the current element is larger than the next one, they are swapped.
- After the first pass, the largest element is at the end of the array, and
can be left alone for the next iteration.

Conclusion
These three examples show how quadratic sorting algorithms work in
C++ without using functions. Such algorithms are easy to understand
and implement, but their efficiency leaves much to be desired when
working with large arrays.

You might also like