Showing posts with label Sort. Show all posts
Showing posts with label Sort. Show all posts

Sunday, 13 March 2022

Java: Merge sort iterative implementation

MergeSort.java

package com.sample.app.algos;

import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;

public class MergeSort {
	private MergeSort() {
	
	}

	public static <T> void sort(List<T> list, Comparator<? super T> comparator) {

		if (list == null || list.size() < 2) {
			return;
		}

		if (comparator == null) {
			throw new IllegalArgumentException("Comparator must be supplied");
		}

		Object[] arr = list.toArray();
		sortIteratively(arr, (Comparator) comparator);

		ListIterator<T> listIterator = list.listIterator();
		for (Object ele : arr) {
			listIterator.next();
			listIterator.set((T) ele);
		}
	}

	private static <T> void sortIteratively(T[] array, Comparator<? super T> comparator) {

		T[] aux = array.clone();

		for (int blockSize = 1; blockSize < array.length; blockSize = (blockSize << 1)) {
			for (int start = 0; start < array.length; start += (blockSize << 1)) {
				merge(array, aux, start, start + blockSize, start + (blockSize << 1), comparator);
			}
		}
	}

	private static <T> void merge(T[] arr, T[] aux, int from, int mid, int to, Comparator<? super T> cmp) {
		if (mid >= arr.length) {
			return;
		}
		if (to > arr.length) {
			to = arr.length;
		}
		int i = from;
		int j = mid;
		for (int k = from; k < to; k++) {
			if (i == mid) {
				aux[k] = arr[j++];
			} else if (j == to) {
				aux[k] = arr[i++];
			} else if (cmp.compare(arr[j], arr[i]) < 0) {
				aux[k] = arr[j++];
			} else {
				aux[k] = arr[i++];
			}
		}
		System.arraycopy(aux, from, arr, from, to - from);
	}
}

 

MergeSortDemo.java

package com.sample.app.algos;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class MergeSortDemo {

	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(5, 46, 25, 13, 12);

		MergeSort.sort(list, new Comparator<Integer>() {

			@Override
			public int compare(Integer data1, Integer data2) {
				return data1.compareTo(data2);
			}
		});

		for (Integer data : list) {
			System.out.println(data);
		}
	}

}

 



Output

5
12
13
25
46

 


You may like

Thursday, 15 April 2021

Spring jpa: Get top N records in given order using repository method

public List<Employee> findTop3ByOrderByIdAsc();

Get top 3 records order by id in ascending order.

 

public List<Employee> findTop3ByOrderByIdDesc();

Get top 3 records order by id in descending order.

 

public List<Employee> findTop3ByOrderByFirstNameAscIdDesc();

Get top 3 records order by firstName in ascending order and id in descending order.

 

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project ‘get-top-n-records’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>get-top-n-records</artifactId>
  <version>1</version>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>


  <dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>


    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>


  </dependencies>
</project>

Step 3: Create application.properties file under src/main/resources folder.

 

application.properties

logging.level.root=WARN
logging.level.org.hibernate=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3


Step 4: Define Employee entity.

 

Employee.java

package com.sample.app.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "my_employee")
public class Employee {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  @Column(name = "first_name")
  private String firstName;

  @Column(name = "last_name")
  private String lastName;

  @Column(name = "age")
  private int age;

  @Column(name = "salary")
  private double salary;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public double getSalary() {
    return salary;
  }

  public void setSalary(double salary) {
    this.salary = salary;
  }

  public static EmployeeBuilder builder() {
    return new EmployeeBuilder();
  }

  public static class EmployeeBuilder {
    private Employee emp;

    public EmployeeBuilder() {
      emp = new Employee();
    }

    public EmployeeBuilder firstName(String firstName) {
      emp.setFirstName(firstName);
      return this;
    }

    public EmployeeBuilder lastName(String lastName) {
      emp.setLastName(lastName);
      return this;
    }

    public EmployeeBuilder age(int age) {
      emp.setAge(age);
      return this;
    }

    public EmployeeBuilder salary(double salary) {
      emp.setSalary(salary);
      return this;
    }

    public Employee build() {
      return emp;
    }
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
        .append(lastName).append(", age=").append(age).append(", salary=").append(salary).append("]");
    return builder.toString();
  }

}


Step 5: Define EmployeeRepository interface.

 

EmployeeRepository.java

package com.sample.app.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.sample.app.entity.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Integer>{
  public List<Employee> findTop3ByOrderByIdAsc();
  
  public List<Employee> findTop3ByOrderByIdDesc();
  
  public List<Employee> findTop3ByOrderByFirstNameAscIdDesc();
}


Step 6: Define main application class.

 

App.java 

package com.sample.app;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {

  public static void main(String args[]) {
    SpringApplication.run(App.class, args);
  }

  public void printEmployees(Iterable<Employee> emps, String msg) {
    System.out.println(msg);
    for (Employee emp : emps) {
      System.out.println(emp);
    }

    System.out.println();
  }

  @Bean
  public CommandLineRunner demo(EmployeeRepository employeeRepository) {
    return (args) -> {
      Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").age(32).salary(100000.23).build();
      Employee emp2 = Employee.builder().firstName("Ram").lastName("Chelli").age(43).salary(60000).build();
      Employee emp3 = Employee.builder().firstName("Gopi").lastName("Battu").age(45).salary(1000000).build();
      Employee emp4 = Employee.builder().firstName("Ram").lastName("Srikanth").age(39).salary(60000).build();
      Employee emp5 = Employee.builder().firstName("Surendra").lastName("Sami").age(32).salary(100000.23).build();

      employeeRepository.save(emp1);
      employeeRepository.save(emp2);
      employeeRepository.save(emp3);
      employeeRepository.save(emp4);
      employeeRepository.save(emp5);

      Iterable<Employee> emps = employeeRepository.findTop3ByOrderByIdAsc();
      printEmployees(emps, "Top 3 records order by id in ascending order.");
      
      emps = employeeRepository.findTop3ByOrderByIdDesc();
      printEmployees(emps, "Top 3 records order by id in descending order");
      
      emps = employeeRepository.findTop3ByOrderByFirstNameAscIdDesc();
      printEmployees(emps, "Top 3 records order by firstName in ascending order and id in descending order");

    };
  }

}

Total project structure looks like below.

 


 

Run App.java, you will see below messages in console.

 

Top 3 records order by id in ascending order.
Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23]
Employee [id=2, firstName=Ram, lastName=Chelli, age=43, salary=60000.0]
Employee [id=3, firstName=Gopi, lastName=Battu, age=45, salary=1000000.0]

Top 3 records order by id in descending order
Employee [id=5, firstName=Surendra, lastName=Sami, age=32, salary=100000.23]
Employee [id=4, firstName=Ram, lastName=Srikanth, age=39, salary=60000.0]
Employee [id=3, firstName=Gopi, lastName=Battu, age=45, salary=1000000.0]

Top 3 records order by firstName in ascending order and id in descending order
Employee [id=3, firstName=Gopi, lastName=Battu, age=45, salary=1000000.0]
Employee [id=4, firstName=Ram, lastName=Srikanth, age=39, salary=60000.0]
Employee [id=2, firstName=Ram, lastName=Chelli, age=43, salary=60000.0]










 

 

 

Previous                                                    Next                                                    Home

Tuesday, 6 April 2021

Php: rsort: Sort array contents in descending order

‘rsort’ function return the elements in descending order (in place, affect the original array).

 

Syntax

rsort($array_name);

 

Example

rsort($arr);

 

Find the below working example.

 

array_reverse_sort_demo.php

#!/usr/bin/php

<?php

    $arr = array(22, 31, -5, 77, -98, 18);
    
    echo "Original array : \n";
    print_r($arr);

    rsort($arr);

    echo "Sorted array in descending order : \n";
    print_r($arr);
    
?>

 

Output

$./array_reverse_sort_demo.php 

Original array : 
Array
(
    [0] => 22
    [1] => 31
    [2] => -5
    [3] => 77
    [4] => -98
    [5] => 18
)
Sorted array in descending order : 
Array
(
    [0] => 77
    [1] => 31
    [2] => 22
    [3] => 18
    [4] => -5
    [5] => -98
)

 

 

 

 

Previous                                                    Next                                                    Home

Monday, 5 April 2021

Php: sort: Sort the elements of array in ascending order

‘sort’ function return the elements in ascending order (in place, affect the original array).

 

Syntax

sort($array_name);

 

Example

sort($arr);

 

Find the below working example.

 

array_sort_demo.php

#!/usr/bin/php

<?php

    $arr = array(22, 31, -5, 77, -98, 18);
    
    echo "Original array : \n";
    print_r($arr);

    sort($arr);

    echo "Sorted array in ascending order : \n";
    print_r($arr);
    
?>

 

Output

$./array_sort_demo.php 

Original array : 
Array
(
    [0] => 22
    [1] => 31
    [2] => -5
    [3] => 77
    [4] => -98
    [5] => 18
)
Sorted array in ascending order : 
Array
(
    [0] => -98
    [1] => -5
    [2] => 18
    [3] => 22
    [4] => 31
    [5] => 77
)

 

 

 

 

Previous                                                    Next                                                    Home

Monday, 13 April 2020

TableSaw: Sort elements of table in both ascending and descending order

Minus sign preceding the name of column, used to sort the column in descending order.

Example
Table sorted = table.sortOn("FirstName", "-LastName");

Above statement sort the elements by ‘FirstName’ in ascending order and ‘LastName’ in descending order.

App.java
package com.sample.app;

import tech.tablesaw.api.IntColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;

public class App {

  public static void main(String args[]) {
    int[] empIds = { 1, 2, 3, 4, 5, 6 };
    String[] firstNames = { "Hari", "Ram", "Sowmya", "Chamu", "Swethank", "Chamu" };
    String[] lastNames = { "Krishna", "Gurram", "Maj", "Maj", "Baji", "Gurram" };

    Table table = Table.create().addColumns(IntColumn.create("Employee Id", empIds))
        .addColumns(StringColumn.create("FirstName", firstNames))
        .addColumns(StringColumn.create("LastName", lastNames));

    Table sorted = table.sortOn("FirstName", "-LastName");
    
    System.out.println(table.print());
    System.out.println("\nAfter Sorting\n");
    System.out.println(sorted.print());
    
  }
}

Output

Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           4  |      Chamu  |       Maj  |
           5  |   Swethank  |      Baji  |
           6  |      Chamu  |    Gurram  |

After Sorting

 Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           4  |      Chamu  |       Maj  |
           6  |      Chamu  |    Gurram  |
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           5  |   Swethank  |      Baji  |


Previous                                                    Next                                                    Home

TableSaw: Sort the elements of a table

‘sortOn’ method is used to sort the elements of a table based on column contents.

public Table sortOn(String... columnNames)
public Table sortOn(int... columnIndexes)

Example
Table sorted = table.sortOn("FirstName", "LastName");

App.java
package com.sample.app;

import tech.tablesaw.api.IntColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;

public class App {

  public static void main(String args[]) {
    int[] empIds = { 1, 2, 3, 4, 5, 6 };
    String[] firstNames = { "Hari", "Ram", "Sowmya", "Chamu", "Swethank", "Chamu" };
    String[] lastNames = { "Krishna", "Gurram", "Maj", "Maj", "Baji", "Gurram" };

    Table table = Table.create().addColumns(IntColumn.create("Employee Id", empIds))
        .addColumns(StringColumn.create("FirstName", firstNames))
        .addColumns(StringColumn.create("LastName", lastNames));

    Table sorted = table.sortOn("FirstName", "LastName");
    
    System.out.println(table.print());
    System.out.println(sorted.print());
    
  }
}

Output
Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           4  |      Chamu  |       Maj  |
           5  |   Swethank  |      Baji  |
           6  |      Chamu  |    Gurram  |
 Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           6  |      Chamu  |    Gurram  |
           4  |      Chamu  |       Maj  |
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           5  |   Swethank  |      Baji  |


‘sortOn’ method sorts the elements in ascending order. If you want to sort the elements of table in descending order, you can use 'sortDescendingOn' method.

Example
Table sorted = table.sortDescendingOn("FirstName", "LastName");

App.java

package com.sample.app;

import tech.tablesaw.api.IntColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;

public class App {

  public static void main(String args[]) {
    int[] empIds = { 1, 2, 3, 4, 5, 6 };
    String[] firstNames = { "Hari", "Ram", "Sowmya", "Chamu", "Swethank", "Chamu" };
    String[] lastNames = { "Krishna", "Gurram", "Maj", "Maj", "Baji", "Gurram" };

    Table table = Table.create().addColumns(IntColumn.create("Employee Id", empIds))
        .addColumns(StringColumn.create("FirstName", firstNames))
        .addColumns(StringColumn.create("LastName", lastNames));

    Table sorted = table.sortDescendingOn("FirstName", "LastName");
    
    System.out.println(table.print());
    System.out.println("\nAfter Sorting\n");
    System.out.println(sorted.print());
    
  }
}

Output

Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           4  |      Chamu  |       Maj  |
           5  |   Swethank  |      Baji  |
           6  |      Chamu  |    Gurram  |

After Sorting

 Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           5  |   Swethank  |      Baji  |
           3  |     Sowmya  |       Maj  |
           2  |        Ram  |    Gurram  |
           1  |       Hari  |   Krishna  |
           4  |      Chamu  |       Maj  |
           6  |      Chamu  |    Gurram  |


Previous                                                    Next                                                    Home