Recapitulare: Algoritmi

Noţiunea de algoritm. Proprietăţi. Ordinul unui algoritm

Sortarea prin interschimbare
procedure interschimbare( A ) for each i in 0 to length(A) – 2 for each j in i + 1 to length(A) - 1 if A[i] > A[j] then swap( A[i], A[j] ) end if end for end for end procedure

Bubble-sort
procedure bubbleSort( A ) do swapped = false for each i in 1 to length(A) - 1 if A[i-1] > A[i] then swap( A[i-1], A[i] ) swapped = true end if end for while swapped end procedure

Quicksort
Varianta cu spaţiu suplimentar de memorie (clasică) function quicksort(array) var list less, greater if length(array) ≤ 1 return array select and remove a pivot value pivot from array for each x in array if x ≤ pivot then append x to less else append x to greater return concatenate(quicksort(less), pivot, quicksort(greater))

2 variante cu interschimbare “pe loc” Cu posibilitate de alegere a pivotului function partition(array, left, right, pivotIndex) pivotValue := array[pivotIndex] swap array[pivotIndex] and array[right] // Move pivot to end storeIndex := left for i from left to right - 1 // left ≤ i < right if array[i] ≤ pivotValue swap array[i] and array[storeIndex] storeIndex := storeIndex + 1 swap array[storeIndex] and array[right] // Move pivot to its final place return storeIndex procedure quicksort(array, left, right) if right > left select a pivot index //(e.g. pivotIndex := left + (right - left)/2) pivotNewIndex := partition(array, left, right, pivotIndex) quicksort(array, left, pivotNewIndex - 1) quicksort(array, pivotNewIndex + 1, right) Cu setarea pivotului la jumătatea vecorului function quicksort(array, left, right) var pivot, leftIdx = left, rightIdx = right if right - left > 0 pivot = (left + right) / 2 while leftIdx <= pivot and rightIdx >= pivot while array[leftIdx] < array[pivot] and leftIdx <= pivot leftIdx = leftIdx + 1 while array[rightIdx] > array[pivot] and rightIdx >= pivot rightIdx = rightIdx - 1; swap array[leftIdx] with array[rightIdx] leftIdx = leftIdx + 1 rightIdx = rightIdx - 1 if leftIdx - 1 == pivot pivot = rightIdx = rightIdx + 1 else if rightIdx + 1 == pivot pivot = leftIdx = leftIdx - 1 quicksort(array, left, pivot - 1) quicksort(array, pivot + 1, right)

Algoritmi nedeterminişti
Exemple de algoritmi nedeterminişti 1. Căutarea în vector j = choice(1…n) if A(j) ==x print x; success else print “esec”; failure 2. Sortarea unui vector procedure Nsort(A) array B for i = 0 to n B[i] = 0 for i = 0 to n j = choice (1…n) if B[j] != 0 then failure B[j] = A[i] for i = 0 to n - 1 if B[i] > B[i + 1] then failure print B success Ce ordin au algoritmii nedeterminişti?

Sign up to vote on this title
UsefulNot useful