Spaces:
Configuration error
Configuration error
File size: 10,818 Bytes
5c8f53e 30e4290 5c8f53e bd2c426 5c8f53e bd2c426 5c8f53e 8b76633 5c8f53e 8b76633 5c8f53e 8b76633 5c8f53e 8b76633 5c8f53e 8b76633 5c8f53e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 |
# algorithms.py with metrics
import math
import time
def _snap(steps, record_steps, a, active_i, boundary=-1):
if record_steps:
steps.append(
{"array": a.copy(), "active_index": active_i, "sorted_boundary": boundary}
)
def insertion_sort(arr, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
start = time.perf_counter()
for i in range(1, len(a)):
key = a[i]
j = i - 1
# at least one comparison if entering the while loop
while j >= 0:
comparisons += 1
if a[j] > key:
a[j + 1] = a[j]
moves += 1
_snap(steps, record_steps, a, j + 1, i)
j -= 1
else:
break
a[j + 1] = key
moves += 1
_snap(steps, record_steps, a, j + 1, i)
end = time.perf_counter()
metrics = {"comparisons": comparisons, "moves": moves, "seconds": end - start}
return steps, metrics
def merge_sort(arr, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
start = time.perf_counter()
def merge(left, mid, right):
nonlocal comparisons, moves
# Create copies of subarrays
left_part = a[left : mid + 1]
right_part = a[mid + 1 : right + 1]
i = j = 0
k = left
# Merge while both parts have elements
while i < len(left_part) and j < len(right_part):
comparisons += 1 # one comparison each loop
if left_part[i] <= right_part[j]:
a[k] = left_part[i]
moves += 1
_snap(steps, record_steps, a, k, right)
i += 1
else:
a[k] = right_part[j]
moves += 1
_snap(steps, record_steps, a, k, right)
j += 1
k += 1
# Copy remaining elements of left_part
while i < len(left_part):
a[k] = left_part[i]
moves += 1
_snap(steps, record_steps, a, k, right)
i += 1
k += 1
# Copy remaining elements of right_part
while j < len(right_part):
a[k] = right_part[j]
moves += 1
_snap(steps, record_steps, a, k, right)
j += 1
k += 1
def sort(left, right):
if left >= right:
return
mid = (left + right) // 2
sort(left, mid)
sort(mid + 1, right)
merge(left, mid, right)
if len(a) > 0:
sort(0, len(a) - 1)
end = time.perf_counter()
metrics = {"comparisons": comparisons, "moves": moves, "seconds": end - start}
return steps, metrics
def quick_sort(arr, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
def swap(i, j, *, active_i=None, sorted_b=None):
nonlocal moves
if i == j:
return
(
a[i],
a[j],
) = (
a[j],
a[i],
)
moves += 2
_snap(
steps,
record_steps,
a,
i if active_i is None else active_i,
-1 if sorted_b is None else sorted_b,
)
def partition(low, high):
nonlocal comparisons, moves
pivot = a[high]
i = low - 1
# compare high-1 and pivot
for j in range(low, high):
comparisons += 1
if a[j] <= pivot:
i += 1
swap(i, j, active_i=j)
# put pivot back to place
swap(i + 1, high, active_i=i + 1, sorted_b=i + 1)
return i + 1
def qs(low, high):
if low < high:
p = partition(low, high)
qs(low, p - 1)
qs(p + 1, high)
start = time.perf_counter()
if a:
qs(0, len(a) - 1)
seconds = time.perf_counter() - start
metrics = {"comparisons": comparisons, "moves": moves, "seconds": seconds}
return steps, metrics
def counting_sort(arr, k=None, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
if not a:
return steps, {"comparisons": 0, "moves": 0, "seconds": 0.0}
# negatifleri desteklemiyorsak koruma (istersen offset ile destekleyebilirsin)
if min(a) < 0:
raise ValueError("Counting Sort: negatif değerler desteklenmiyor.")
# k (değer aralığı) verilmediyse max+1 al
if k is None:
k = max(a) + 1
start = time.perf_counter()
count = [0] * k
for v in a:
count[v] += 1
for i in range(1, k):
count[i] += count[i - 1]
out = [0] * len(a)
for v in reversed(a):
count[v] -= 1
out[count[v]] = v
for i, v in enumerate(out):
a[i] = v
moves += 1
_snap(steps, record_steps, a, i, i)
seconds = time.perf_counter() - start
return steps, {"comparisons": comparisons, "moves": moves, "seconds": seconds}
def radix_sort_lsd(arr, base=10, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
if not a:
return steps, {"comparisons": 0, "moves": 0, "seconds": 0.0}
if base < 2:
raise ValueError("radix base must be >= 2")
start = time.perf_counter()
def digit(x, exp):
return (x // exp) % base
exp = 1
maxv = max(a)
# for each digit place
while maxv // exp > 0:
# stable counting sort by current digit
count = [0] * base
# count
for v in a:
d = digit(v, exp)
count[d] += 1
# prefix sums
for i in range(1, base):
count[i] += count[i - 1]
# build output(scan from right)
out = [0] * len(a)
for i in range(len(a) - 1, -1, -1):
v = a[i]
d = digit(v, exp)
count[d] -= 1
out[count[d]] = v
for i, v in enumerate(out):
a[i] = v
moves += 1
_snap(steps, record_steps, a, i, i)
exp *= base
seconds = time.perf_counter() - start
metrics = {"comparisons": comparisons, "moves": moves, "seconds": seconds}
return steps, metrics
# --- Heap Sort (max-heap, in-place) with metrics & step recording ---
# steps: her adımda {"array": a.copy(), "active_index": i, "sorted_boundary": b}
# - active_index: o karede yeni yazılan / swap’e giren indeks
# - sorted_boundary: heapsort’ta sıralı kuyruk (suffix) başlangıcı; j >= boundary -> "sorted"
# metrics:
# - comparisons: her a[l] > a[m] veya a[r] > a[m] kontrolü 1 karşılaştırma
# - moves: diziye her yazma 1; swap 2 move
def heap_sort(arr, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
heap_sorted = -1
def snapshot(active_i, boundary):
_snap(steps, record_steps, a, active_i, boundary)
def swap(i, j):
nonlocal moves
if i == j:
return
a[i], a[j] = a[j], a[i]
moves += 2
snapshot(i, heap_sorted)
def heapify(n, i):
nonlocal comparisons
while True:
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n:
comparisons += 1
if a[l] > a[largest]:
largest = l
if r < n:
comparisons += 1
if a[r] > a[largest]:
largest = r
if largest == i:
break
swap(i, largest)
i = largest
start = time.perf_counter()
n = len(a)
if n <= 1:
metrics = {"comparisons": 0, "moves": 0, "seconds": 0.0}
return steps, metrics
# build max heap
for i in range(n // 2 - 1, -1, -1):
heapify(n, i)
# extract max
for end in range(n - 1, 0, -1):
swap(0, end)
heap_sorted = end
heapify(end, 0)
seconds = time.perf_counter() - start
metrics = {"comparisons": comparisons, "moves": moves, "seconds": seconds}
return steps, metrics
def shell_sort(arr, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
def snap(active_i, boundary=-1):
_snap(steps, record_steps, a, active_i, boundary)
start = time.perf_counter()
n = len(a)
if n <= 1:
return steps, {"comparisons": 0, "moves": 0, "seconds": 0.0}
gap = n // 2
while gap > 0:
for i in range(gap, n):
key = a[i]
j = i - gap
while j >= 0:
comparisons += 1
if a[j] > key:
a[j + gap] = a[j]
moves += 1
snap(j + gap)
j -= gap
else:
break
a[j + gap] = key
moves += 1
snap(j + gap)
gap //= 2
seconds = time.perf_counter() - start
metrics = {"comparisons": comparisons, "moves": moves, "seconds": seconds}
return steps, metrics
def bucket_sort(arr, num_buckets=None, record_steps: bool = True):
a = arr.copy()
steps = []
comparisons = 0
moves = 0
if not a:
return steps, {"comparisons": 0, "moves": 0, "seconds": 0.0}
n = len(a)
if num_buckets is None:
num_buckets = max(1, int(math.sqrt(n)))
start = time.perf_counter()
maxv = max(a)
# normlize values range between 0 and 1
if maxv == 0:
seconds = time.perf_counter() - start
for i, v in enumerate(a):
_snap(steps, record_steps, a, i, i)
return steps, {"comparisons": 0, "moves": 0, "seconds": seconds}
normalized = [x / (maxv + 1.0) for x in a]
# create buckets
buckets = [[] for _ in range(num_buckets)]
# split values to buckets
for v_norm, v_orig in zip(normalized, a):
idx = int(v_norm * num_buckets)
if idx >= num_buckets:
idx = num_buckets - 1
buckets[idx].append(v_orig)
# sort buckets
for b in buckets:
for i in range(1, len(b)):
key = b[i]
j = i - 1
while j >= 0:
comparisons += 1
if b[j] > key:
b[j + 1] = b[j]
j -= 1
else:
break
b[j + 1] = key
# save at main
write_i = 0
for b in buckets:
for v in b:
a[write_i] = v
moves += 1
_snap(steps, record_steps, a, write_i, write_i)
write_i += 1
seconds = time.perf_counter() - start
metrics = {"comparisons": comparisons, "moves": moves, "seconds": seconds}
return steps, metrics
|