-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArmstrongPrimeSort.java
More file actions
78 lines (70 loc) · 2.11 KB
/
Copy pathArmstrongPrimeSort.java
File metadata and controls
78 lines (70 loc) · 2.11 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
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.Scanner;
public class ArmstrongPrimeSort {
//METHOD TO PRINT ARRAY
static void display(int a[]){
for(int i=0; i<a.length; i++){
System.out.print(a[i] + " ");
}
}
//METHOD TO SWAP TARGET ARRAY ELEMENTS
static void swap(int a[], int i, int j){
int temp= a[i];
a[i]= a[j];
a[j]= temp;
}
//METHOD TO SORT ARMSTRONG NUMBERS TO THE LEFT AND PRIME NUMBERS TO THE RIGHT
static void sortArmstrongPrime(int a[]){
int left=0, right= a.length-1;
while(left<right){
//CHECK IF THE LEFT ELEMENT IS ARMSTRONG
int left_copy= a[left];
int sum=0;
while(left_copy>0){
int rem= left_copy%10;
sum= sum+(rem*rem*rem);
left_copy/=10;
}
//CHECK IF THE RIGHT ELEMENT IS PRIME
boolean flag= true;
int prime=0;
for(int j=2; j<a[right]; j++){
if(a[right]%j==0){
flag=false;
break;
}
}
if(flag==true){
prime=a[right];
}
//CONDITIONS FOR SORTING ARMSTRONG TO THE LEFT AND PRIME TO THE RIGHT
if(a[left]==sum){
left++;
}
else if(a[right]==prime){
right--;
}
else{
swap(a, left, right);
if(a[left]==sum){
left++;
}
else if(a[right]==prime){
right--;
}
}
}
display(a);
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
//INPUT ARRAY SIZE AND ELEMENTS
System.out.print("Enter array size: ");
int size= sc.nextInt();
int arr[]= new int[size];
System.out.print("Enter " + size + " numbers: ");
for(int i=0; i<arr.length; i++){
arr[i]= sc.nextInt(); /*13 153 4 370 11 6*/
}
sortArmstrongPrime(arr);
}
}