WeixiangYan/CodeTransOcean huggingface dataset:
Task: Roots of unity







Python: import cmath


class Complex(complex):
    def __repr__(self):
        rp = '%7.5f' % self.real if not self.pureImag() else ''
        ip = '%7.5fj' % self.imag if not self.pureReal() else ''
        conj = '' if (
            self.pureImag() or self.pureReal() or self.imag < 0.0
        ) else '+'
        return '0.0' if (
            self.pureImag() and self.pureReal()
        ) else rp + conj + ip

    def pureImag(self):
        return abs(self.real) < 0.000005

    def pureReal(self):
        return abs(self.imag) < 0.000005


def croots(n):
    if n <= 0:
        return None
    return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
    
    


for nr in range(2, 11):
    print(nr, list(croots(nr)))





Ada: with Ada.Text_IO;                 use Ada.Text_IO;
with Ada.Float_Text_IO;           use Ada.Float_Text_IO;
with Ada.Numerics.Complex_Types;  use Ada.Numerics.Complex_Types;

procedure Roots_Of_Unity is
   Root : Complex;
begin
   for N in 2..10 loop
      Put_Line ("N =" & Integer'Image (N));
      for K in 0..N - 1 loop
         Root :=
             Compose_From_Polar
             (  Modulus  => 1.0,
                Argument => Float (K),
                Cycle    => Float (N)
             );
            
         Put ("   k =" & Integer'Image (K) & ", ");
         if Re (Root) < 0.0 then
            Put ("-");
         else
            Put ("+");
         end if;
         Put (abs Re (Root), Fore => 1, Exp => 0);
         if Im (Root) < 0.0 then
            Put ("-");
         else
            Put ("+");
         end if;
         Put (abs Im (Root), Fore => 1, Exp => 0);
         Put_Line ("i");
      end loop;
   end loop;
end Roots_Of_Unity;
Task: Roots of unity








VB: Public Sub roots_of_unity()
    For n = 2 To 9
        Debug.Print n; "th roots of 1:"
        For r00t = 0 To n - 1
            Debug.Print "   Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
                Sin(2 * WorksheetFunction.Pi() * r00t / n))
        Next r00t
        Debug.Print
    Next n
End Sub




Ada: with Ada.Text_IO;                 use Ada.Text_IO;
with Ada.Float_Text_IO;           use Ada.Float_Text_IO;
with Ada.Numerics.Complex_Types;  use Ada.Numerics.Complex_Types;

procedure Roots_Of_Unity is
   Root : Complex;
begin
   for N in 2..10 loop
      Put_Line ("N =" & Integer'Image (N));
      for K in 0..N - 1 loop
         Root :=
             Compose_From_Polar
             (  Modulus  => 1.0,
                Argument => Float (K),
                Cycle    => Float (N)
             );
            
         Put ("   k =" & Integer'Image (K) & ", ");
         if Re (Root) < 0.0 then
            Put ("-");
         else
            Put ("+");
         end if;
         Put (abs Re (Root), Fore => 1, Exp => 0);
         if Im (Root) < 0.0 then
            Put ("-");
         else
            Put ("+");
         end if;
         Put (abs Im (Root), Fore => 1, Exp => 0);
         Put_Line ("i");
      end loop;
   end loop;
end Roots_Of_Unity;
Task: Roots of unity

C: #include <stdio.h>
#include <math.h>

int main()
{
	double a, c, s, PI2 = atan2(1, 1) * 8;
	int n, i;

	for (n = 1; n < 10; n++) for (i = 0; i < n; i++) {
		c = s = 0;
		if (!i )		c =  1;
		else if(n == 4 * i)	s =  1;
		else if(n == 2 * i)	c = -1;
		else if(3 * n == 4 * i)	s = -1;
		else
			a = i * PI2 / n, c = cos(a), s = sin(a);

		if (c) printf("%.2g", c);
		printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s);
		printf(i == n - 1 ?"\n":",  ");
	}

	return 0;
}
Task: Roots of unity



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

class Program
{
    static IEnumerable<Complex> RootsOfUnity(int degree)
    {
        return Enumerable
            .Range(0, degree)
            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
    }

    static void Main()
    {
        var degree = 3;
        foreach (var root in RootsOfUnity(degree))
        {
            Console.WriteLine(root);
        }
    }
}
Task: Roots of unity


C++: #include <complex>
#include <cmath>
#include <iostream>

double const pi = 4 * std::atan(1);

int main()
{
  for (int n = 2; n <= 10; ++n)
  {
    std::cout << n << ": ";
    for (int k = 0; k < n; ++k)
      std::cout << std::polar(1, 2*pi*k/n) << " ";
    std::cout << std::endl;
  }
}
Task: Roots of unity





Java: import java.util.Locale;

public class Test {

    public static void main(String[] a) {
        for (int n = 2; n < 6; n++)
            unity(n);
    }

    public static void unity(int n) {
        System.out.printf("%n%d: ", n);

        
        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {

            double real = Math.cos(angle); 

            if (Math.abs(real) < 1.0E-3)
                real = 0.0; 

            double imag = Math.sin(angle); 

            if (Math.abs(imag) < 1.0E-3)
                imag = 0.0;

            System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
        }
    }
}
Task: Roots of unity







Python: import cmath


class Complex(complex):
    def __repr__(self):
        rp = '%7.5f' % self.real if not self.pureImag() else ''
        ip = '%7.5fj' % self.imag if not self.pureReal() else ''
        conj = '' if (
            self.pureImag() or self.pureReal() or self.imag < 0.0
        ) else '+'
        return '0.0' if (
            self.pureImag() and self.pureReal()
        ) else rp + conj + ip

    def pureImag(self):
        return abs(self.real) < 0.000005

    def pureReal(self):
        return abs(self.imag) < 0.000005


def croots(n):
    if n <= 0:
        return None
    return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
    
    


for nr in range(2, 11):
    print(nr, list(croots(nr)))
Task: Roots of unity








VB: Public Sub roots_of_unity()
    For n = 2 To 9
        Debug.Print n; "th roots of 1:"
        For r00t = 0 To n - 1
            Debug.Print "   Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
                Sin(2 * WorksheetFunction.Pi() * r00t / n))
        Next r00t
        Debug.Print
    Next n
End Sub
Task: Roots of unity




Go: package main

import (
    "fmt"
    "math"
    "math/cmplx"
)

func main() {
    for n := 2; n <= 5; n++ {
        fmt.Printf("%d roots of 1:\n", n)
        for _, r := range roots(n) {
            fmt.Printf("  %18.15f\n", r)
        }
    }
}

func roots(n int) []complex128 {
    r := make([]complex128, n)
    for i := 0; i < n; i++ {
        r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
    }
    return r
}
Task: Roots of unity



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

class Program
{
    static IEnumerable<Complex> RootsOfUnity(int degree)
    {
        return Enumerable
            .Range(0, degree)
            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
    }

    static void Main()
    {
        var degree = 3;
        foreach (var root in RootsOfUnity(degree))
        {
            Console.WriteLine(root);
        }
    }
}








Fortran: PROGRAM Roots

  COMPLEX :: root 
  INTEGER :: i, n
  REAL :: angle, pi

  pi = 4.0 * ATAN(1.0)
  DO n = 2, 7
    angle = 0.0
    WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
    DO i = 1, n
      root = CMPLX(COS(angle), SIN(angle))
      WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j  "
      angle = angle + (2.0*pi / REAL(n))
    END DO
    WRITE(*,*)
  END DO

END PROGRAM Roots
Task: Roots of unity


C++: #include <complex>
#include <cmath>
#include <iostream>

double const pi = 4 * std::atan(1);

int main()
{
  for (int n = 2; n <= 10; ++n)
  {
    std::cout << n << ": ";
    for (int k = 0; k < n; ++k)
      std::cout << std::polar(1, 2*pi*k/n) << " ";
    std::cout << std::endl;
  }
}









Fortran: PROGRAM Roots

  COMPLEX :: root 
  INTEGER :: i, n
  REAL :: angle, pi

  pi = 4.0 * ATAN(1.0)
  DO n = 2, 7
    angle = 0.0
    WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
    DO i = 1, n
      root = CMPLX(COS(angle), SIN(angle))
      WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j  "
      angle = angle + (2.0*pi / REAL(n))
    END DO
    WRITE(*,*)
  END DO

END PROGRAM Roots
Task: Roots of unity

C: #include <stdio.h>
#include <math.h>

int main()
{
	double a, c, s, PI2 = atan2(1, 1) * 8;
	int n, i;

	for (n = 1; n < 10; n++) for (i = 0; i < n; i++) {
		c = s = 0;
		if (!i )		c =  1;
		else if(n == 4 * i)	s =  1;
		else if(n == 2 * i)	c = -1;
		else if(3 * n == 4 * i)	s = -1;
		else
			a = i * PI2 / n, c = cos(a), s = sin(a);

		if (c) printf("%.2g", c);
		printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s);
		printf(i == n - 1 ?"\n":",  ");
	}

	return 0;
}










Fortran: PROGRAM Roots

  COMPLEX :: root 
  INTEGER :: i, n
  REAL :: angle, pi

  pi = 4.0 * ATAN(1.0)
  DO n = 2, 7
    angle = 0.0
    WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
    DO i = 1, n
      root = CMPLX(COS(angle), SIN(angle))
      WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j  "
      angle = angle + (2.0*pi / REAL(n))
    END DO
    WRITE(*,*)
  END DO

END PROGRAM Roots
Task: Roots of unity





Java: import java.util.Locale;

public class Test {

    public static void main(String[] a) {
        for (int n = 2; n < 6; n++)
            unity(n);
    }

    public static void unity(int n) {
        System.out.printf("%n%d: ", n);

        
        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {

            double real = Math.cos(angle); 

            if (Math.abs(real) < 1.0E-3)
                real = 0.0; 

            double imag = Math.sin(angle); 

            if (Math.abs(imag) < 1.0E-3)
                imag = 0.0;

            System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
        }
    }
}






Fortran: PROGRAM Roots

  COMPLEX :: root 
  INTEGER :: i, n
  REAL :: angle, pi

  pi = 4.0 * ATAN(1.0)
  DO n = 2, 7
    angle = 0.0
    WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
    DO i = 1, n
      root = CMPLX(COS(angle), SIN(angle))
      WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j  "
      angle = angle + (2.0*pi / REAL(n))
    END DO
    WRITE(*,*)
  END DO

END PROGRAM Roots
Task: Roots of unity







Python: import cmath


class Complex(complex):
    def __repr__(self):
        rp = '%7.5f' % self.real if not self.pureImag() else ''
        ip = '%7.5fj' % self.imag if not self.pureReal() else ''
        conj = '' if (
            self.pureImag() or self.pureReal() or self.imag < 0.0
        ) else '+'
        return '0.0' if (
            self.pureImag() and self.pureReal()
        ) else rp + conj + ip

    def pureImag(self):
        return abs(self.real) < 0.000005

    def pureReal(self):
        return abs(self.imag) < 0.000005


def croots(n):
    if n <= 0:
        return None
    return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
    
    


for nr in range(2, 11):
    print(nr, list(croots(nr)))




Fortran: PROGRAM Roots

  COMPLEX :: root 
  INTEGER :: i, n
  REAL :: angle, pi

  pi = 4.0 * ATAN(1.0)
  DO n = 2, 7
    angle = 0.0
    WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
    DO i = 1, n
      root = CMPLX(COS(angle), SIN(angle))
      WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j  "
      angle = angle + (2.0*pi / REAL(n))
    END DO
    WRITE(*,*)
  END DO

END PROGRAM Roots
Task: Roots of unity








VB: Public Sub roots_of_unity()
    For n = 2 To 9
        Debug.Print n; "th roots of 1:"
        For r00t = 0 To n - 1
            Debug.Print "   Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
                Sin(2 * WorksheetFunction.Pi() * r00t / n))
        Next r00t
        Debug.Print
    Next n
End Sub



Fortran: PROGRAM Roots

  COMPLEX :: root 
  INTEGER :: i, n
  REAL :: angle, pi

  pi = 4.0 * ATAN(1.0)
  DO n = 2, 7
    angle = 0.0
    WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
    DO i = 1, n
      root = CMPLX(COS(angle), SIN(angle))
      WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j  "
      angle = angle + (2.0*pi / REAL(n))
    END DO
    WRITE(*,*)
  END DO

END PROGRAM Roots
Task: HTTPS



C#: using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        var client = new WebClient();
        var data = client.DownloadString("https:

        Console.WriteLine(data);
    }
}









Ada: with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;
Task: HTTPS

C: #include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
CURL *curl;
char buffer[CURL_ERROR_SIZE];
int main(void) {
    if ((curl = curl_easy_init()) != NULL) {
        curl_easy_setopt(curl, CURLOPT_URL, "https:
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
        if (curl_easy_perform(curl) != CURLE_OK) {
            fprintf(stderr, "%s\n", buffer);
            return EXIT_FAILURE;
        }
        curl_easy_cleanup(curl);
    }
    return EXIT_SUCCESS;
}











Ada: with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;
Task: HTTPS




Go: package main

import (
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    r, err := http.Get("https:
    if err != nil {
        log.Fatalln(err)
    }
    io.Copy(os.Stdout, r.Body)
}








Ada: with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;
Task: HTTPS





Java: URL url = new URL("https:
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());

while (scanner.hasNext()) {
    System.out.println(scanner.next());
}







Ada: with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;
Task: HTTPS







Python: import urllib.request
print(urllib.request.urlopen("https://sourceforge.net/").read())





Ada: with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;
Task: HTTPS








VB: Option Explicit

Const sURL="https://sourceforge.net/"

Dim oHTTP
Set oHTTP = CreateObject("Microsoft.XmlHTTP")

On Error Resume Next
oHTTP.Open "GET", sURL, False
oHTTP.Send ""
If Err.Number = 0 Then
     WScript.Echo oHTTP.responseText
Else
     Wscript.Echo "error " & Err.Number & ": " & Err.Description
End If

Set oHTTP = Nothing




Ada: with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;
Task: HTTPS

C: #include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
CURL *curl;
char buffer[CURL_ERROR_SIZE];
int main(void) {
    if ((curl = curl_easy_init()) != NULL) {
        curl_easy_setopt(curl, CURLOPT_URL, "https:
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
        if (curl_easy_perform(curl) != CURLE_OK) {
            fprintf(stderr, "%s\n", buffer);
            return EXIT_FAILURE;
        }
        curl_easy_cleanup(curl);
    }
    return EXIT_SUCCESS;
}
Task: HTTPS



C#: using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        var client = new WebClient();
        var data = client.DownloadString("https:

        Console.WriteLine(data);
    }
}
Task: HTTPS





Java: URL url = new URL("https:
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());

while (scanner.hasNext()) {
    System.out.println(scanner.next());
}
Task: HTTPS







Python: import urllib.request
print(urllib.request.urlopen("https://sourceforge.net/").read())
Task: HTTPS








VB: Option Explicit

Const sURL="https://sourceforge.net/"

Dim oHTTP
Set oHTTP = CreateObject("Microsoft.XmlHTTP")

On Error Resume Next
oHTTP.Open "GET", sURL, False
oHTTP.Send ""
If Err.Number = 0 Then
     WScript.Echo oHTTP.responseText
Else
     Wscript.Echo "error " & Err.Number & ": " & Err.Description
End If

Set oHTTP = Nothing
Task: HTTPS




Go: package main

import (
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    r, err := http.Get("https:
    if err != nil {
        log.Fatalln(err)
    }
    io.Copy(os.Stdout, r.Body)
}
Task: HTTPS






PHP: echo file_get_contents('https://sourceforge.net');
Task: HTTPS






PHP: echo file_get_contents('https://sourceforge.net');






Ada: with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;
Task: Sorting algorithms_Insertion sort



C#: namespace Sort {
  using System;

  static class InsertionSort<T> where T : IComparable {
    public static void Sort(T[] entries) {
      Sort(entries, 0, entries.Length - 1);
    }

    public static void Sort(T[] entries, Int32 first, Int32 last) {
      for (var i = first + 1; i <= last; i++) {
        var entry = entries[i];
        var j = i;

        while (j > first && entries[j - 1].CompareTo(entry) > 0)
          entries[j] = entries[--j];

        entries[j] = entry;
      }
    }
  }
}









Ada: type Data_Array is array(Natural range <>) of Integer;
 
procedure Insertion_Sort(Item : in out Data_Array) is
   First : Natural := Item'First;
   Last  : Natural := Item'Last;
   Value : Integer;
   J     : Integer;
begin
   for I in (First + 1)..Last loop
      Value := Item(I);
      J := I - 1;
      while J in Item'range and then Item(J) > Value loop
         Item(J + 1) := Item(J);
         J := J - 1;
      end loop;
      Item(J + 1) := Value;
   end loop;
end Insertion_Sort;
Task: Sorting algorithms_Insertion sort

C: #include <stdio.h>

void insertion_sort(int*, const size_t); 

void insertion_sort(int *a, const size_t n) {
	for(size_t i = 1; i < n; ++i) {
		int key = a[i];
		size_t j = i;
		while( (j > 0) && (key < a[j - 1]) ) {
			a[j] = a[j - 1];
			--j;
		}
		a[j] = key;
	}
}

int main (int argc, char** argv) {

    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};

    const size_t n = sizeof(a) / sizeof(a[0]) ;   

    for (size_t i = 0; i < n; i++)
        printf("%d%s", a[i], (i == (n - 1))? "\n" : " ");

    insertion_sort(a, n);

    for (size_t i = 0; i < n; i++)
        printf("%d%s", a[i], (i == (n - 1))? "\n" : " ");

    return 0;
}











Ada: type Data_Array is array(Natural range <>) of Integer;
 
procedure Insertion_Sort(Item : in out Data_Array) is
   First : Natural := Item'First;
   Last  : Natural := Item'Last;
   Value : Integer;
   J     : Integer;
begin
   for I in (First + 1)..Last loop
      Value := Item(I);
      J := I - 1;
      while J in Item'range and then Item(J) > Value loop
         Item(J + 1) := Item(J);
         J := J - 1;
      end loop;
      Item(J + 1) := Value;
   end loop;
end Insertion_Sort;
Task: Sorting algorithms_Insertion sort


C++: #include <algorithm>
#include <iostream>
#include <iterator>



template <typename RandomAccessIterator, typename Predicate>
void insertion_sort(RandomAccessIterator begin, RandomAccessIterator end,
                    Predicate p) {
  for (auto i = begin; i != end; ++i) {
    std::rotate(std::upper_bound(begin, i, *i, p), i, i + 1);
  }
}


template <typename RandomAccessIterator>
void insertion_sort(RandomAccessIterator begin, RandomAccessIterator end) {
  insertion_sort(begin, end, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>());
}


int main() {

  int a[] = { 100, 2, 56, 200, -52, 3, 99, 33, 177, -199 };

  insertion_sort(std::begin(a), std::end(a));

  
  
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  
std::cout << "\n";
}










Ada: type Data_Array is array(Natural range <>) of Integer;
 
procedure Insertion_Sort(Item : in out Data_Array) is
   First : Natural := Item'First;
   Last  : Natural := Item'Last;
   Value : Integer;
   J     : Integer;
begin
   for I in (First + 1)..Last loop
      Value := Item(I);
      J := I - 1;
      while J in Item'range and then Item(J) > Value loop
         Item(J + 1) := Item(J);
         J := J - 1;
      end loop;
      Item(J + 1) := Value;
   end loop;
end Insertion_Sort;
Task: Sorting algorithms_Insertion sort




Go: package main

import "fmt"

func insertionSort(a []int) {
    for i := 1; i < len(a); i++ {
        value := a[i]
        j := i - 1
        for j >= 0 && a[j] > value {
            a[j+1] = a[j]
            j = j - 1
        }
        a[j+1] = value
    }
}

func main() {
    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    fmt.Println("unsorted:", list)

    insertionSort(list)
    fmt.Println("sorted!  ", list)
}








Ada: type Data_Array is array(Natural range <>) of Integer;
 
procedure Insertion_Sort(Item : in out Data_Array) is
   First : Natural := Item'First;
   Last  : Natural := Item'Last;
   Value : Integer;
   J     : Integer;
begin
   for I in (First + 1)..Last loop
      Value := Item(I);
      J := I - 1;
      while J in Item'range and then Item(J) > Value loop
         Item(J + 1) := Item(J);
         J := J - 1;
      end loop;
      Item(J + 1) := Value;
   end loop;
end Insertion_Sort;
Task: Sorting algorithms_Insertion sort





Java: public static void insertSort(int[] A){
  for(int i = 1; i < A.length; i++){
    int value = A[i];
    int j = i - 1;
    while(j >= 0 && A[j] > value){
      A[j + 1] = A[j];
      j = j - 1;
    }
    A[j + 1] = value;
  }
}







Ada: type Data_Array is array(Natural range <>) of Integer;
 
procedure Insertion_Sort(Item : in out Data_Array) is
   First : Natural := Item'First;
   Last  : Natural := Item'Last;
   Value : Integer;
   J     : Integer;
begin
   for I in (First + 1)..Last loop
      Value := Item(I);
      J := I - 1;
      while J in Item'range and then Item(J) > Value loop
         Item(J + 1) := Item(J);
         J := J - 1;
      end loop;
      Item(J + 1) := Value;
   end loop;
end Insertion_Sort;
Task: Sorting algorithms_Insertion sort







Python: def insertion_sort(L):
    for i in xrange(1, len(L)):
        j = i-1 
        key = L[i]
        while j >= 0 and L[j] > key:
           L[j+1] = L[j]
           j -= 1
        L[j+1] = key





Ada: type Data_Array is array(Natural range <>) of Integer;
 
procedure Insertion_Sort(Item : in out Data_Array) is
   First : Natural := Item'First;
   Last  : Natural := Item'Last;
   Value : Integer;
   J     : Integer;
begin
   for I in (First + 1)..Last loop
      Value := Item(I);
      J := I - 1;
      while J in Item'range and then Item(J) > Value loop
         Item(J + 1) := Item(J);
         J := J - 1;
      end loop;
      Item(J + 1) := Value;
   end loop;
end Insertion_Sort;