diff --git a/Heapsort.py b/Heapsort.py new file mode 100644 index 0000000..67f6907 --- /dev/null +++ b/Heapsort.py @@ -0,0 +1,43 @@ +#python heap Sort + +#function of heapify +#n=size of heap +def heapify(arr, n, i): + largest = i #initialize the largest as the root + l = 2 * i + 1#check child of left = 2*i + 1 + r = 2 * i + 2#check child of right = 2*i + 2 + + #if left child of root exists and > than root + if l < n and arr[largest] < arr[l]: + largest = l + + #if right child of root exists and > than root + if r < n and arr[largest] < arr[r]: + largest = r + + #changing the root to largest + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] + #heapify the root. + heapify(arr, n, largest) + +#function heapsort to sort +def heapSort(arr): + n = len(arr) + + #build the maxheap. + for i in range(n//2 - 1, -1, -1): + heapify(arr, n, i) + + #extracting the elements + for i in range(n-1, 0, -1): + arr[i], arr[0] = arr[0], arr[i] + heapify(arr, i, 0) + + +#---main program-- +arr = [12, 11, 13, 5, 6, 7] +print("Array we entering: ",arr) +heapSort(arr) +print() +print("Sorted array is",arr) diff --git a/QuickSort.py b/QuickSort.py new file mode 100644 index 0000000..d196a63 --- /dev/null +++ b/QuickSort.py @@ -0,0 +1,47 @@ +#quick sort algorithm + +arr=[] +n=int(input("Enter the array size: ")) +def userinputs(arr): + for i in range(n): + v= int((input("Enter a number: ")))#add the elements to the array + arr.append(v) + +def partition(arr,start,end): + i=(start-1)#getting the index of the smallest element + pivot=arr[end] #get an elemt to check + + for j in range(start,end): + if(arr[j]<=pivot): #if current element <=pivot + i=i+1 #increment the index of smallest element + arr[i],arr[j]=arr[j],arr[i] #swap the elements + #exchanging + arr[i+1],arr[end]=arr[end],arr[i+1] + return(i+1) + +def quickSort(arr,start,end): + if (start