Sort by

recency

|

624 Discussions

|

  • + 0 comments

    JavaScript

    function bubbleSort(array: number[]): void {
        let endPosition: number = array.length - 1;
        let numberOfSwaps: number = 0;
        let swapPosition: number;
    
        while (endPosition > 0) {
            swapPosition = 0;
    
            for (let i = 0; i < array.length - 1; i++) {
                if (array[i] > array[i + 1]) {
                    [array[i], array[i + 1]] = [array[i + 1], array[i]];
                    swapPosition = i;
                    numberOfSwaps++;
                }
            }
            endPosition = swapPosition;
            
        } 
        console.log(`Array is sorted in ${numberOfSwaps} swaps.`);
        console.log(`First Element: ${array[0]}`);
        console.log(`Last Element: ${array[array.length - 1]}`);
    }
    
    function main() {
        const n: number = parseInt(readLine().trim(), 10);
    
        const a: number[] = readLine().replace(/\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10));
    
        bubbleSort(a);
    }
    
  • + 0 comments
    if __name__ == '__main__':
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
        swap=0
        for i in range(n):
            for j in range(n-i-1):
                if a[j]>a[j+1]:
                    swap+=1
                    a[j],a[j+1]=a[j+1],a[j]
        print(f'Array is sorted in {swap} swaps.')
        print(f'First Element: {a[0]}')
        print(f'Last Element: {a[-1]}')
    
  • + 0 comments
    n = int(input().strip())
    a = list(map(int, input().rstrip().split()))
    c=0
    for x in range(n-2,-1,-1):
        for i in range(0,x+1):
            if a[i]>a[i+1]:
                t=a[i] 
                a[i]=a[i+1]
                a[i+1]=t   
                c+=1
    print(f"Array is sorted in {c} swaps.")
    print(f"First Element: {a[0]}")
    print(f"Last Element: {a[-1]}")
    
  • + 0 comments

    Python 3 code if name == 'main': n = int(input().strip())

    a = list(map(int, input().rstrip().split()))
    
    swapy = 0
    for i in range(n):
        for j in range(n-1):
            wartosc = int()
            if (a[j] > a[j + 1]):
                wartosc = a[j]
                a[j] = a[j + 1]
                a[j + 1] = wartosc
                swapy += 1
    
    print("Array is sorted in "+str(swapy)+ " swaps.")
    print("First Element: " +str(a[0]))
    print("Last Element: " + str(a[-1]))
    
  • + 0 comments

    Python Code:

    if __name__ == '__main__':
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
        
        swap = 0
        for i in range(n):
            for j in range(i, n):
                if a[i]>a[j]:
                    a[i], a[j] = a[j], a[i]
                    swap+=1
                    
        print(f"Array is sorted in {swap} swaps.")
        print(f"First Element: {a[0]}")
        print(f"Last Element: {a[-1]}")