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

algorithm-pseudocode

The document provides pseudocode for various sorting algorithms including Merge Sort, Counting Sort, Insertion Sort, and Quick Sort, as well as algorithms for finding Hamiltonian cycles and solving the N-Queens problem using backtracking. Each algorithm is explained with its steps, time complexity, and specific functions. Additionally, it highlights the backtracking approach used in the Hamiltonian Cycle and N-Queens problems to efficiently explore potential solutions.

Uploaded by

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

algorithm-pseudocode

The document provides pseudocode for various sorting algorithms including Merge Sort, Counting Sort, Insertion Sort, and Quick Sort, as well as algorithms for finding Hamiltonian cycles and solving the N-Queens problem using backtracking. Each algorithm is explained with its steps, time complexity, and specific functions. Additionally, it highlights the backtracking approach used in the Hamiltonian Cycle and N-Queens problems to efficiently explore potential solutions.

Uploaded by

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

MErgeSort Pseudocode: Hamiltonian Cycle Algorithm:

function mergeSort(A, left, right):


if left < right: function hamiltonianCycle(G, path, pos):
mid = (left + right) // 2 if pos == V:
mergeSort(A, left, mid) # Check if the last vertex is connected to the first
mergeSort(A, mid + 1, right) if G[path[pos - 1]][path[0]] == 1:
merge(A, left, mid, right) return true
function merge(A, left, mid, right): else:
n1 = mid - left + 1 return false
n2 = right - mid
L = [A[left + i] for i in range(n1)] # Try different vertices as candidates for the next position in the path
R = [A[mid + 1 + j] for j in range(n2)] for v in range(1, V): # Start from vertex 1 (vertex 0 is already in the path)
i, j, k = 0, 0, left if isSafe(v, G, path, pos):
while i < n1 and j < n2: path[pos] = v # Add vertex to the path
if L[i] <= R[j]: if hamiltonianCycle(G, path, pos + 1): # Recur for the next position
A[k] = L[i] return true
i += 1 path[pos] = -1 # Backtrack: remove the vertex
else:
A[k] = R[j] return false # No vertex can be added to the Hamiltonian Cycle
j += 1
k += 1 function isSafe(v, G, path, pos):
while i < n1: # Check if this vertex is adjacent to the last vertex in the path
A[k] = L[i] if G[path[pos - 1]][v] == 0:
i += 1 return false
k += 1 # Check if the vertex is already in the path
while j < n2: for i in range(pos):
A[k] = R[j] if path[i] == v:
j += 1 return false
k += 1 return true
function main():
A = [unsorted array] function main():
mergeSort(A, 0, len(A) - 1) V = number of vertices
print(A) # Output the sorted array G = adjacency matrix of the graph
path = [-1] * V # Initialize path with -1
path[0] = 0 # Start at vertex 0
Count sort:
if not hamiltonianCycle(G, path, 1):
CountingSort(A, k) print("No Hamiltonian Cycle exists")
Input: A -> Array of n elements, k -> Maximum value in A else:
Output: Sorted array print("Hamiltonian Cycle:", path + [path[0]]) # Include the starting vertex

1. Create a count array C of size (k + 1), initialized to 0. 1. Initialization:


2. For each element x in A: Start the cycle from vertex 0 and initialize the path array.
Increment C[x]. 2. Backtracking:
3. For i = 1 to k: Try to add each vertex to the path, ensuring it is adjacent to the last vertex in the path and
C[i] += C[i - 1]. has not been visited yet.
4. Create an output array B of the same size as A. Recurse for the next position in the path.
5. For each element x in A (processed in reverse order): If adding a vertex leads to a dead-end, backtrack and try the next vertex.
Place x at index C[x] - 1 in B. 3.Cycle Check:
Decrement C[x]. When all vertices are included in the path, check if the last vertex is adjacent to the first to
6. Copy elements from B back to A. complete the cycle.
7. Return A. 4.Termination:
Time Complexity: If a Hamiltonian cycle is found, print the path; otherwise, report that no cycle exists.
Counting the occurrences: 𝑂(𝑛)O(n) Time Complexity
Building the cumulative counts: 𝑂(𝑘)
Placing elements in the output array: O(n) Worst Case:
Total Time Complexity: 𝑂(𝑛+𝑘) , where:n = number of elements in the array. O(V!), where V is the number of vertices, as every permutation of vertices may need to be
k = range of input values (maximum value in the array). checked.
Backtracking significantly reduces the search space by pruning invalid paths.

InsertionSort:

Step 1 − If it is the first element, it is already sorted. return 1; QuickSort:


Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list Steps:
Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be Divide: Partition the array into two subarrays such that:
sorted Elements less than or equal to the pivot are on the left.
Step 5 − Insert the value Elements greater than the pivot are on the right.
Step 6 − Repeat until list is sorted Conquer: Recursively apply QuickSort to the left and right subarrays.
Pseudocode Combine: Combine the sorted subarrays (no extra work is needed because the array is
Algorithm: Insertion-Sort(A) sorted in place).
for j = 2 to A.length
key = A[j] function quickSort(A, low, high):
i=j–1 if low < high:
while i > 0 and A[i] > key # Partition the array and get the pivot index
A[i + 1] = A[i] pivotIndex = partition(A, low, high)
i = i -1
A[i + 1] = key # Recursively sort elements before and after the pivot
quickSort(A, low, pivotIndex - 1)
quickSort(A, pivotIndex + 1, high)
8 queen problem using Backtracking:
function partition(A, low, high):
Algorithm: pivot = A[high] # Choose the last element as the pivot
1.Place queens one by one in each row. i = low - 1 # Index of the smaller element
2.For the current row, try placing the queen in each column.
Check if placing the queen at the current position is safe: for j in range(low, high): # Iterate over the array
No other queen in the same column. if A[j] <= pivot:
No other queen on the same diagonal. i += 1
3.If safe, place the queen and proceed to place the next queen in the next row. swap(A[i], A[j]) # Swap elements smaller than or equal to the pivot
4. If placing the queen leads to a conflict (i.e., no safe position in the row), backtrack by
removing the queen from the previous row and trying a different position. swap(A[i + 1], A[high]) # Move the pivot to its correct position
5. Repeat until all queens are placed or all possibilities are exhausted. return i + 1 # Return the pivot index

Backtracking Pseudocode: # Main function


function solveNQueens(board, row): function main():
if row == N: # Base case: all queens placed A = [unsorted array]
printSolution(board) quickSort(A, 0, len(A) - 1)
return true print(A) # Output the sorted array
for col in range(0, N): # Try all columns in the current row
if isSafe(board, row, col): # Check if placing queen is safe
board[row][col] = 1 # Place the queen Average Case (O(nlogn)):
if solveNQueens(board, row + 1): # Recur for next row On average, the pivot divides the array into two subarrays of roughly equal size.
return true Total comparisons per level: O(n).
board[row][col] = 0 # Backtrack: Remove the queen Recursion depth: O(logn).
return false # No valid position for queen in this row
Average Time Complexity Derivation:
function isSafe(board, row, col): Let T(n) represent the time complexity for sorting n elements.
# Check column
for i in range(0, row): Average partitioning divides the array into two parts of size
if board[i][col] == 1: k and n−k−1, with k varying from 0 to n−1.
return false
for i, j in range(row, col, -1): T(n) = T(k) + T(n-k-1) + O(n)
if board[i][j] == 1:
return false Taking an average over all k, the recurrence simplifies to: T(n) = O(n \log n)
for i, j in range(row, col + 1):
if board[i][j] == 1:
return false
return true

function main():
N = 8 # Board size
board = [[0 for _ in range(N)] for _ in range(N)] # Initialize empty board
if not solveNQueens(board, 0): # Start from the first row
print("No solution exists")

You might also like