Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views2 pages

Sel Sort

Uploaded by

ashakotadiya6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Sel Sort

Uploaded by

ashakotadiya6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Got it!

Let's implement the swapping mechanism without using the tuple swap syntax arr[i],
arr[min_idx] = arr[min_idx], arr[i]. We'll use a temporary variable instead.

Python Program for Selec on Sort Using Classes and Objects

class Selec onSort:

def __init__(self, arr):

self.arr = arr

def sort(self):

n = len(self.arr)

for i in range(n):

min_index = i

for j in range(i + 1, n):

if self.arr[j] < self.arr[min_index]:

min_index = j

# Swap elements using a temporary variable

temp = self.arr[i]

self.arr[i] = self.arr[min_index]

self.arr[min_index] = temp

def display(self):

return self.arr

# Example usage

arr = [64, 25, 12, 22, 11]

sorter = Selec onSort(arr)

print("Original array:", sorter.display())

sorter.sort()

print("Sorted array:", sorter.display())

Explana on:

1. Selec onSort Class:


o __init__(self, arr): Ini alizes the class with the array to be sorted.

o sort(self): Implements the selec on sort algorithm.

 Outer loop iterates over each element in the array.

 Inner loop finds the minimum element in the unsorted part of the array.

 Swap the found minimum element using a temporary variable:

 Store the element at posi on i in a temporary variable temp.

 Assign the minimum element to posi on i.

 Assign the value of temp to the posi on of the minimum element.

o display(self): Returns the array (useful for prin ng before and a er sor ng).

Example Usage:

 Ini alize the array arr = [64, 25, 12, 22, 11].

 Create an instance of the Selec onSort class with sorter = Selec onSort(arr).

 Print the original array with sorter.display().

 Call sorter.sort() to sort the array.

 Print the sorted array with sorter.display().

By swapping elements using a temporary variable, we ensure clarity in the swapping mechanism.
This method is straigh orward and should help in understanding how elements are exchanged
during the sor ng process.

Feel free to test and modify the program as needed! If you have any ques ons or need further
assistance, let me know.

You might also like