-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergesort.zig
More file actions
65 lines (54 loc) · 1.53 KB
/
Copy pathmergesort.zig
File metadata and controls
65 lines (54 loc) · 1.53 KB
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
const std = @import("std");
fn mergeSort(arr: []f64) []f64 {
const len = arr.len;
if (len <= 1) {
return arr;
}
const mid = len / 2;
const leftHalf = arr[0..mid];
const rightHalf = arr[mid..];
var leftSorted = mergeSort(leftHalf);
var rightSorted = mergeSort(rightHalf);
var sortedArr = []f64{};
var i: usize = 0;
var j: usize = 0;
while (i < leftSorted.len) | j < rightSorted.len |
{
if (j == rightSorted.len)
{
sortedArr.append(leftSorted[i]);
i += 1;
} else if (i < leftSorted.len && leftSorted[i] <= rightSorted[j])
{
sortedArr.append(leftSorted[i]);
i += 1;
} else
{
sortedArr.append(rightSorted[j]);
j += 1;
}
}
return sortedArr;
}
pub fn main() void {
const allocator = std.testing.allocator;
var unsortedList = []f64{};
while (true) {
const input = std.io.getline("Enter an element: ", allocator);
if (input == "y" or input == "Y") {
const element = try f64.tryParse(std.io.readLine("Enter a number: "));
if (element == null) {
std.debug.print("Invalid number entered\n", .{});
continue;
}
unsortedList.append(element.*);
} else {
break;
}
}
const sortedList = mergeSort(unsortedList);
for (sortedList) |element| {
std.debug.print("{} ", .{element});
}
std.debug.print("\n", .{});
}