5-Sort Alghrithem 2
5-Sort Alghrithem 2
Ma:H.A.S
Review
06/26/2024
Ma:H.A.S
Divide and Conquer
06/26/2024
Ma:H.A.S
ترتيب االختيار
06/26/2024
Ma:H.A.S
Selection sort
06/26/2024
Ma:H.A.S
Ex:
06/26/2024
Ma:H.A.S
First pass:
• For the first position in the sorted array, the whole array is traversed from
index 0 to 4 sequentially. The first position where 64 is stored presently,
after traversing whole array it is clear that 11 is the lowest value.
• Thus, replace 64 with 11. After one iteration 11, which happens to be the
least value in the array, tends to appear in the first position of the sorted
list.
06/26/2024
Ma:H.A.S
Second Pass:
• For the second position, where 25 is present, again traverse the rest of the
array in a sequential manner.
• After traversing, we found that 12 is the second lowest value in the array
and it should appear at the second place in the array, thus swap these
values.
06/26/2024
Ma:H.A.S
Third Pass:
• Now, for third place, where 25 is present again traverse the rest of the
array and find the third least value present in the array.
• While traversing, 22 came out to be the third least value and it should
appear at the third place in the array, thus swap 22 with element present
at third position.
06/26/2024
Ma:H.A.S
Fourth pass:
• Similarly, for fourth position traverse the rest of the array and find the
fourth least element in the array
• As 25 is the 4th lowest value hence, it will place at the fourth position.
06/26/2024
Ma:H.A.S
Fifth Pass:
• At last the largest value present in the array automatically get placed at
the last position in the array
• The resulted array is the sorted array.
06/26/2024
Ma:H.A.S
Code
• // C++ program for implementation of • // Function to print an array
• // selection sort • void printArray(int arr[], int size)
• #include <bits/stdc++.h> • {
• using namespace std; • int i;
• for (i = 0; i < size; i++) {
• // Function for Selection sort • cout << arr[i] << " ";
• void selectionSort(int arr[], int n)
• cout << endl;
• {
• }
• int i, j, min_idx;
• }
• // One by one move boundary of
• // unsorted subarray
• // Driver program
• for (i = 0; i < n - 1; i++) { • int main()
• {
• // Find the minimum element in • int arr[] = { 64, 25, 12, 22, 11 };
• // unsorted array • int n = sizeof(arr) / sizeof(arr[0]);
• min_idx = i;
• for (j = i + 1; j < n; j++) { • // Function Call
• if (arr[j] < arr[min_idx]) • selectionSort(arr, n);
• min_idx = j; • cout << "Sorted array: \n";
• } • printArray(arr, n);
• return 0;
• // Swap the found minimum element • }
• // with the first element
• if (min_idx != i)
• // This is code is contributed by rathbhupendra
• swap(arr[min_idx], arr[i]);
06/26/2024
• }
Ma:H.A.S
الكود البرمجي
• // Selection Sort
• int a[] = {100,35,500,9,67,20};
• int n=6;
• int min_index;
• for (int i=0; i <n-1; i++)
• {
• min_index = i ;
• for (int j = i ; j <n ; j++)
• if (a[j] < a [min_index])
• min_index = j;
• swap (a[i] , a[min_index]);
•
•
• }
• printArray(a, n);
• return 0;
• }
06/26/2024
Ma:H.A.S
شرح الكود
06/26/2024
Ma:H.A.S
Complexity Analysis of Selection Sort
• Advantages
• Simple and easy to understand.
• Works well with small datasets.
• Disadvantages
• Selection sort has a time complexity of O(n^2) in
the worst and average case.
• Does not work well on large datasets.
• Does not preserve the relative order of items with
equal keys which means it is not stable.
06/26/2024
Ma:H.A.S
Insertion Sort
06/26/2024
Ma:H.A.S
Insertion Sort
• 11 12 13 5 6
06/26/2024
Ma:H.A.S
Second Pass:
• 11 12 13 5 6
• 11 12 13 5 6
• Both 5 and 13 are not present at their correct place so swap them
• 11 12 5 13 6
• After swapping, elements 12 and 5 are not sorted, thus swap again
• 11 5 12 13 6
• 5 11 12 13 6
06/26/2024
Ma:H.A.S
Fourth Pass:
• Now, the elements which are present in the sorted sub-array are 5, 11 and 12
• Moving to the next two elements 13 and 6
• 5 11 12 13 6
• Clearly, they are not sorted, thus perform swap between both
• 5 11 12 6 13
• 5 11 6 12 13
• 5 6 11 12 13
06/26/2024
Ma:H.A.S
Illustrations:
06/26/2024
Ma:H.A.S
Pseudo Code of Insertion Sort
• procedure insertionSort(arr):
• for i = 1 to n-1
• key = arr[i]
• j = i-1
• while j >= 0 and arr[j] > key
• swap arr[j+1] with arr[j]
• j=j-1
• end while
• end for
• end function
06/26/2024
Ma:H.A.S
Insertion Sort Algorithm – Iterative Approach
06/26/2024
Ma:H.A.S
Insertion Sort Algorithm – Iterative Approach
06/26/2024
Ma:H.A.S
Code in c lang
• #include <iostream>
• #include <vector> • void printArray(vector<int>& arr, int n)
• using namespace std;
• {
• void recursiveInsertionSort(vector<int>& arr, int n) • for (int i = 0; i < n; i++)
• {
• {
• // Base case: if the array has only one element, it is already
sorted • cout << arr[i] << " ";
• if (n <= 1) { • }
• return;
• } • cout << endl;
• // Sort the first n-1 elements of the array recursively • }
• recursiveInsertionSort(arr, n - 1);
•
• // Insert the nth element into its correct position in the sorted • int main()
subarray
• {
• int last = arr[n - 1];
• int j = n - 2; • vector<int> arr = {12, 11, 13, 5, 6};
•
• int n = arr.size();
• // Shift elements to the right to make space for the nth element
• while (j >= 0 && arr[j] > last)
• { • recursiveInsertionSort(arr, n);
• arr[j + 1] = arr[j];
• printArray(arr, n);
• j--;
• }
•
• return 0;
• // Place the nth element in its correct position
06/26/2024 • }
• arr[j + 1] = last;
Ma:H.A.S
• }
06/26/2024
Ma:H.A.S
Insertion Sort ترتيب اإلدراج
Consider the following observations:
– A list with one element is sorted
– In general, if we have a sorted list of k -1 items, we
can insert a new item to create a sorted list of size k
For example, consider this sorted array containing of eight
sorted entries
5 7 12 19 21 26 33 40 14 9 18 21 2
Ma:H.A.S
Insertion Sort ترتيب اإلدراج.
Ma:H.A.S
06/26/2024
Ma:H.A.S
Insertion Sort ترتيب اإلدراج.
Ma:H.A.S
Insertion Sort Algorithm
n 1 n n 1
Thus, the worst-case run time is k O n2
k 1 2
Ma:H.A.S
Insertion
06/26/2024
Ma:H.A.S
Insertion VS selection
06/26/2024
Ma:H.A.S
Bubble Sort
• In this algorithm,
• traverse from left and compare adjacent elements and the higher one
is placed at right side.
• In this way, the largest element is moved to the rightmost end at first.
• This process is then continued to find the second largest and place it
and so on until the data is sorted.
06/26/2024
Ma:H.A.S
How does Bubble Sort Work?
First Pass:
06/26/2024
Ma:H.A.S
Second Pass:
Place the second largest element at correct
position
06/26/2024
Ma:H.A.S
Third Pass:
06/26/2024
Ma:H.A.S
Implementation of Bubble Sort
• Bubble sort has a time complexity of O(N2) which makes it very slow for
large data sets.
• Bubble sort is a comparison-based sorting algorithm, which means that it
requires a comparison operator to determine the relative order of elements in
the input data set. It can limit the efficiency of the algorithm in certain cases.
06/26/2024
Ma:H.A.S
الترتيب الفقاعي
06/26/2024
Ma:H.A.S
متابعة
• تقارن هذه الخوارزمية بين قيم الخانات المتجاورة ،تبدأ بالمقارنة بين أول خانتين من
المصفوفة ،إذا كان محتوى الخانة األولى أكبر من محتوى الخانة الثانية سيتم تبادل
محتوى الخانتين و هكذا مع بقية الخانات.
• عند انتهاء الدورة األولى ستكون الخوارزمية قد
أنجزت n-1مقارنة و بهذا ستتم إزاحة أكبر عناصر المصفوفة إلى الخانة األخيرة.
بقي اآلن ترتيب الــ n-1عنصر .و هكذا األمر مع بقية الدورات ..
النتيجة :عملية الترتيب تـخـتلف عن عملية البحث في هذه النقطة ،فالترتيب ال يقبل •
وجود عدة احتماالت في النتيجة ،فعند تطبيق الخوارزمية سنحصل على مصفوفة مرتبة
تصاعديا و بالتالي ال توجد احتماالت للمناقشة.
•
اإليجابيات :الخوارزمية سهلة التصور و بسيطة المفهوم.
السلبيات :بطيئة شيئا ما وغير عملية ،خصوصا عند معالجة المصفوفات الضخمة
06/26/2024
Ma:H.A.S
الكود البرمجي
• #include "stdafx.h"
• #include <iostream>
• #include<string>
• using namespace std;
06/26/2024
Ma:H.A.S
التعقيد الزمني
06/26/2024
Ma:H.A.S
مثال
06/26/2024
Ma:H.A.S
Quick Sort
06/26/2024
Ma:H.A.S
How does Quick Sort work?
• The key process in quick Sort is a partition(). The target of partitions is to
place the pivot (any element can be chosen to be a pivot) at its correct
position in the sorted array and put all smaller elements to the left of the
pivot, and all greater elements to the right of the pivot.
• Partition is done recursively on each side of the pivot after the pivot is
placed in its correct position and this finally sorts the array.
06/26/2024
Ma:H.A.S
Step 1
• Consider: arr[] = {10, 80, 30, 90, 40}.
• Compare 10 with the pivot and as it is less than pivot arrange it
accrodingly.
06/26/2024
Ma:H.A.S
Step 2
06/26/2024
Ma:H.A.S
Step 3
06/26/2024
Ma:H.A.S
Step 4
06/26/2024
Ma:H.A.S
Step 5
06/26/2024
Ma:H.A.S
Illustration of Quick sort:
06/26/2024
Ma:H.A.S
Code implementation of the Quick Sort:
• Time Complexity:
• It has a worst-case time complexity of O(N2), which occurs when the pivot is chosen poorly.
• It is not a good choice for small data sets.
• It is not a stable sort, meaning that if two elements have the same key, their relative order will not be
preserved in the sorted output in case of quick sort, because here we are swapping elements according
to the pivot’s position (without considering their original positions).
06/26/2024
Ma:H.A.S
Merge sort ترتيب الدمج
.خوارزمية دمج الفرز هي خوارزمية فرز تعتمد على نموذج فرق تسد •
. يتم تقسيم المصفوفة مبدئًيا إلى نصفين متساويين ثم يتم دمجهما بطريقة مرتبة، في هذه الخوارزمية •
فكر في األمر على أنه خوارزمية متكررة تقسم المصفوفة باستمرار إلى نصفين حتى ال يمكن:دمج عملية الفرز •
فإن القسمة، هذا يعني أنه إذا أصبحت المصفوفة فارغة أو لم يتبق منها سوى عنصر واحد.تقسيمها بشكل أكبر
. أي أنها الحالة األساسية إليقاف العودية، ستتوقف
فقم بتقسيمها إلى نصفين واستدعاء ترتيب الدمج بشكل متكرر على، إذا كانت المصفوفة تحتوي على عناصر متعددة •
عملية الدمج هي عملية أخذ مصفوفتين. يتم تطبيق عملية الدمج، عند فرز كال النصفين، أخيًر ا.كل من النصفين
.صغيرتين مرتبة ودمجهما في النهاية إلنشاء مصفوفة أكبر وبالتالي تتطلب احيانا الى مصفوفة اضافية مساعدة
The Merge Sort algorithm is a sorting algorithm that is based on the Divide and Conquer paradigm. In this
algorithm, the array is initially divided into two equal halves and then they are combined in a sorted
manner.
Merge Sort Working Process:
Think of it as a recursive algorithm continuously splits the array in half until it cannot be further divided.
This means that if the array becomes empty or has only one element left, the dividing will stop, i.e. it is
the base case to stop the recursion. If the array has multiple elements, split the array into halves and
recursively invoke the merge sort on each of the halves. Finally, when both halves are sorted, the merge
operation is applied. Merge operation is the process of taking two smaller sorted arrays and combining
them to eventually make a larger one.
06/26/2024
Ma:H.A.S
Merge Sort Algorithm
• Merge sort is defined as a sorting algorithm that works by dividing an array into smaller
subarrays, sorting each subarray, and then merging the sorted subarrays back together to form
the final sorted array.
• In simple terms, we can say that the process of merge sort is to divide the array into two
halves, sort each half, and then merge the sorted halves back together. This process is
repeated until the entire array is sorted.
• Need for Merge Sort
• One thing that you might wonder is what is the specialty of this algorithm. We already have a
number of sorting algorithms then why do we need this algorithm? One of the main
advantages of merge sort is that it has a time complexity of O(n log n), which means it can sort
large arrays relatively quickly. It is also a stable sort, which means that the order of elements
with equal values is preserved during the sort.
• Merge sort is a popular choice for sorting large datasets because it is relatively efficient and
easy to implement. It is often used in conjunction with other algorithms, such as quicksort, to
improve the overall performance of a sorting routine.
06/26/2024
Ma:H.A.S
Advantages of Merge Sort:
• Stability: Merge sort is a stable sorting algorithm, which means it maintains the relative
order of equal elements in the input array. This makes it useful in applications where
preserving the original order of equal elements is important.
• Guaranteed worst-case performance: Merge sort has a worst-case time complexity of O(n
log n), which means it performs well even on large datasets. Other sorting algorithms, such
as quicksort, have a worst-case time complexity of O(n^2), which can result in poor
performance on large datasets.
• Parallelizable: Merge sort is a naturally parallelizable algorithm, which means it can be
easily parallelized to take advantage of multiple processors or threads. This makes it useful
for high-performance computing applications.
• Memory efficient: Merge sort has a space complexity of O(n), which means it can sort
datasets that are larger than the available memory on a machine. This makes it useful for
applications where memory usage is a concern.
• Versatility: Merge sort can be used to sort a wide range of data types, including integers,
floating-point numbers, and strings.
• Adaptability: Merge sort can be adapted to handle different input distributions, such as
partially sorted, nearly sorted, or completely unsorted data. This makes it useful in a variety
of real-world applications.
06/26/2024
Ma:H.A.S
illustrator
06/26/2024
Ma:H.A.S
Merge Sort
Divide and conquer
Big Problem
Sub- Sub-
Problem Proble
soluation
06/26/2024
Ma:H.A.S
كيف تعمل خوارزمية الدمج؟
نفحص إذا الفهرس اليساري أقل من اليميني •
اآلن ،يقسم فرز الدمج أوًال المصفوفة بأكملها بشكل تكراري إلى نصفين •
متساويين ،ما لم تتحقق القيم الذرية .هنا ،نرى أن مصفوفة مكونة من 7
عناصر مقسمة إلى مصفوفتين بحجم 4و 3على التوالي.
اآلن ،مرة ثانية ،اكتشف أن المؤشر األيسر أقل من الفهرس األيمن لكال •
المصفوفتين ،إذا وجدت نعم ،فقم بحساب النقاط الوسطى لكال المصفوفتين
مرة أخرى.
اآلن ،قّسم هاتين المصفوفتين إلى نصفين إضافيين ،حتى يتم الوصول إلى •
الوحدات الذرية للمصفوفة وال يمكن إجراء مزيد من التقسيم.
06/26/2024
Ma:H.A.S
متابعة
06/26/2024
Ma:H.A.S
EX:
06/26/2024
Ma:H.A.S
تعقيد خوارزمية Merge
•
• )T(n)=n log(n تعقيد الخوارزمية
06/26/2024
Ma:H.A.S
Shell خوارزمية
06/26/2024
Ma:H.A.S
06/26/2024
Ma:H.A.S
Con’t
06/26/2024
Ma:H.A.S
Con’t
06/26/2024
Ma:H.A.S
خطوات الخوارزمية
الخطوات: •
-1ابدأ الخطوة •
- 2تهيئة قيمة حجم الفجوة .مثال h :الخطوة •
- 3قّسم القائمة إلى جزء فرعي أصغر .يجب أن يكون لكل منها فترات متساوية لـ h •
- 4قم بفرز هذه القوائم الفرعية باستخدام فرز اإلدراج •
- 5كرر هذه الخطوة 2حتى يتم فرز القائمة. •
- 6اطبع قائمة مرتبة. •
- 7توقف. •
06/26/2024
Ma:H.A.S
متابعة
هذه الخوارزمية فعالة جًد ا لمجموعات البيانات متوسطة الحجم •
حيث أن متوسط درجة تعقيدها وأسوأ حالة لهذه الخوارزمية يعتمد
على تسلسل الفجوة األكثر شهرة هو ) ، Ο (nحيث nهو عدد
العناصر .وأسوأ حالة تعقيد فضاء هو ) .O (nكيف يعمل Shell
Sort؟ دعونا نفكر في المثال التالي للحصول على فكرة عن كيفية
عمل ترتيب الصدفة .نأخذ نفس المصفوفة التي استخدمناها في
األمثلة السابقة .للحصول على مثالنا وسهولة الفهم ،نأخذ الفاصل
الزمني .4قم بعمل قائمة فرعية افتراضية لجميع القيم الموجودة
في الفاصل الزمني لـ 4وظائف .هذه القيم هي {، 33{ ، }14 ، 35
}27 ، 42{ ، }19و {}44 ، 10
نقارن القيم في كل قائمة فرعية وتبديلها (إذا لزم األمر) في •
المصفوفة األصلية .بعد هذه الخطوة ،يجب أن تبدو المصفوفة
الجديدة هكذا -
06/26/2024
Ma:H.A.S
متابعة
• ثم نأخذ الفترة الزمنية 1وتولد هذه الفجوة قائمتين فرعيتين
}44 ، 33 ، 10 ، 19{ ، }42 ، 35 ، 27 ، 14{ -
• Shell sort is an algorithm that first sorts the elements far apart from
each other and successively reduces the interval between the
elements to be sorted. It is a generalized version of insertion sort.
• In shell sort, elements at a specific interval (gaps) are sorted. The
interval between the elements is gradually decreased based on the
sequence used. The performance of the shell sort depends on the
type of sequence used for a given input array.
• Shell's original sequence: N/2 , N/4 , …, 1
Ma:H.A.S
06/26/2024
Ma:H.A.S
Shell Sort Algorithm analysis
وتعقيد الخوارزمية
Ma:H.A.S
palindrome
06/26/2024
Ma:H.A.S
Algorithms Complexity
06/26/2024
Ma:H.A.S
Exam
06/26/2024
Ma:H.A.S