Skip to content

Commit 3ddd6d0

Browse files
authored
Create Alternative sorting.md
1 parent 48db2a9 commit 3ddd6d0

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Given an array of integers, print the array in such a way that the first element is first maximum and second element is first minimum and so on.
2+
3+
Examples :
4+
5+
Input : arr[] = {7, 1, 2, 3, 4, 5, 6}
6+
Output : 7 1 6 2 5 3 4
7+
8+
Input : arr[] = {1, 6, 9, 4, 3, 7, 8, 2}
9+
Output : 9 1 8 2 7 3 6 4
10+
11+
```Python
12+
def alternateSort(arr, n):
13+
14+
# Sorting the array
15+
arr.sort()
16+
17+
# Printing the last element of array
18+
# first and then first element and then
19+
# second last element and then second
20+
# element and so on.
21+
i = 0
22+
j = n-1
23+
res = []
24+
while (i < j):
25+
26+
res.append(arr[j])
27+
res.append(arr[i])
28+
j-= 1
29+
i+= 1
30+
# If the total element in array is odd
31+
# then print the last middle element.
32+
if (n % 2 != 0):
33+
res.append(arr[i])
34+
return res
35+
36+
# Driver code
37+
arr = [-1,1,2,3,-5]
38+
n = len(arr)
39+
40+
alternateSort(arr, n)
41+
```

0 commit comments

Comments
 (0)