1462. Tricky sorting

 

The sequence of numbers is given. Arrange them in non-decreasing order of the last digit, and in the case of equality of last digits – arrange the numbers in non-decreasing order.

 

Input. The first line contains number n (1 ≤ n ≤ 100), and the second line contains the positive integers not greater than 32000.

 

Output. Print the sequence of numbers ordered as given in problem statement.

 

Sample input

Sample output

7

12 15 43 13 20 1 15

20 1 12 13 43 15 15

 

 

SOLUTION

sorting

 

Algorithm analysis

Implement the comparator to sort the integers.

 

Example

The array of integers is sorted in ascending order of the last digit. Numbers with the same last digit are sorted in ascending order.

 

Algorithm realization

Declare the array.

 

int m[100];

 

Sorting function. Arrange the numbers in non-decreasing order of the last digit. If the last digits of two numbers are the same, then arrange them in non-decreasing order.

 

int f(int a, int b)

{

  if (a % 10 == b % 10) return a < b;

  return a % 10 < b % 10;

}

 

Read the input data.

 

scanf("%d",&n);

for(i = 0; i < n; i++)

  scanf("%d",&m[i]);

 

Sort array of numbers.

 

sort(m,m+n,f);

 

Print the resulting array.

 

for(i = 0; i < n - 1; i++)

  printf("%d ",m[i]);

printf("%d\n",m[n-1]);

 

Java realization

 

import java.util.*;

 

public class Main

{

  public static class MyFun implements Comparator<Integer>

  {

    public int compare(Integer a, Integer b)

    {

      if (a % 10 == b % 10) return a - b;

      else return a % 10 - b % 10;

    }

  }

 

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    int n = con.nextInt();

    Integer m[] = new Integer[n];

    for(int i = 0; i < n; i++) m[i] = con.nextInt();

 

    Arrays.sort(m, new MyFun());

     

    for(int i = 0; i < n; i++) System.out.print(m[i] + " ");

    System.out.println();

    con.close();

  }

}

 

Python realization

 

import sys

from functools import cmp_to_key

 

def compare(a, b):

  if a % 10 == b % 10: return a - b;

  return a % 10 - b % 10;

 

n = int(input())

lst = []

for line in sys.stdin:

  for var in line.split():

    lst.append(int(var))

 

res = sorted(lst, key = cmp_to_key(compare))

print(*res)