Skip to content

Commit 8c08819

Browse files
authored
Merge pull request thuva4#144 from Fcmam5/master
Add Python code for Selection sort and JavaScript code of Kadan's algorithm
2 parents 6d2aa68 + 100ace7 commit 8c08819

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Kadane's/JavaScript/kedane.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Calculates the largest sum of contiguous subarray within a one-dimensional array
3+
* @param {Array} array - One-dimensional array
4+
* @return {Number} currentMax - The largest sum of contiguous subarrays
5+
*/
6+
function kadane(array){
7+
var currentMax = max = 0;
8+
for (var i = 0; i < array.length; i++) {
9+
max = Math.max(0, max + array[i]);
10+
currentMax = Math.max(currentMax, max);
11+
}
12+
return currentMax;
13+
}
14+
15+
var array = [-2, -3, 4, -1, -2, 1, 5, -3];
16+
console.log("Maximum contiguous sum is: " + kadane(array));
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def selection_sort(array):
2+
"""
3+
Selection sort sorts an array by placing the minimum element element
4+
at the beginning of an unsorted array.
5+
:param array A given array
6+
:return the given array sorted
7+
"""
8+
9+
length = len(array)
10+
11+
for i in range(0, length):
12+
min_index = i # Suppose that the first (current) element is the minimum of the unsorted array
13+
14+
for j in range(i+1, length):
15+
# Update min_index when a smaller minimum is found
16+
if array[j] < array[min_index]:
17+
min_index = j
18+
19+
if min_index != i:
20+
# Swap the minimum and the initial minimum positions
21+
array[min_index], array[i] = array[i], array[min_index]
22+
23+
return array
24+
25+
# Example:
26+
if __name__ == '__main__':
27+
example_array = [5, 6, 7, 8, 1, 2, 12, 14]
28+
print(example_array)
29+
print(selection_sort(example_array))

0 commit comments

Comments
 (0)