Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create PancakeSort.java #150

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions Sorting/PancakeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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();
}
}