forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PancakeSort.java
60 lines (56 loc) · 1.49 KB
/
PancakeSort.java
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
import java.util.*;
class Main
{
static void reverseArray(int a[],int n) //This functions reverses the array upto index n
{
int temp[]=new int[n+1]; // temp is the temporary array
for(int i=0;i<=n;i++)
{
temp[i]=a[n-i];
}
for(int i=0;i<=n;i++)
a[i]=temp[i];
}
static int findmax(int a[],int n) //Function to find index of max element upto index n
{
int max=a[0];int j=0; //j stores the index of max element
for(int i=1;i<=n;i++)
if(a[i]>max)
{max=a[i];
j=i;
}
return j;
}
static void pancakesort(int a[],int n)
{ int currentLength;
for(currentLength=n;currentLength>0;--currentLength)
{
int j= findmax(a,currentLength-1);
if(j!=currentLength)
{
reverseArray(a,j);
reverseArray(a,currentLength-1);
}
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,j,k,l,m,n;
n=sc.nextInt();
int array[]=new int[n];
for(i=0;i<n;i++)
array[i]=sc.nextInt();
pancakesort(array,n);
for(i=0;i<n;i++)
System.out.print(array[i]+" ");
System.out.println();
}
}
/*
Input -
5 //Array length
4 3 7 1 2 //Array Elements
Output -
1 2 3 4 7 //Sorted Array
*/